原创2022/9/14小于 1 分钟
加载渲染过程
父beforeCreate -> 父created-> 父beforeMount-> 子beforeCreate -> 子created -> 子beforeMount -> 子mounted -> 父mounted
2020/2/19小于 1 分钟
动态组件
<div id="root">
<component :is="type"></component> <!--其效果如同下面两行被注释的代码-->
<!-- <child-one v-if="type === 'child-one'"></child-one>
<child-two v-if="type === 'child-two'"></child-two> -->
<button @click="handleClick">change</button>
</div>
<script type="text/javascript">
Vue.component('child-one', {
template: '<div>child-one</div>'
})
Vue.component('child-two', {
template: '<div>child-two</div>'
})
var vm = new Vue({
el: '#root',
data: {
type: 'child-one'
},
methods: {
handleClick() {
this.type = this.type === 'child-one' ? 'child-two' : 'child-one'
}
}
})
</script>
2020/2/16大约 2 分钟
插槽
<div id="root">
<child> <!-- 组件标签 -->
<h1>hello</h1>
</child>
</div>
<script type="text/javascript">
Vue.component('child', { // 子组件
template: '<div><slot></slot></div>'
})
var vm = new Vue({
el: '#root'
})
</script>
2020/2/16大约 4 分钟
当组件的嵌套多时,非父子组件间传值就显得复杂,除了使用vuex实现之外,还可以通过Bus(或者叫 总线/发布订阅模式/观察者模式)的方式实现非父子组件间传值。
2020/2/15大约 1 分钟
在组件标签v-on绑定的事件是自定义事件
<div id="root">
<child @click="handleClick"></child> <!--这里click是自定义事件-->
</div>
<script type="text/javascript">
Vue.component('child', {
template: '<button>Child</button>',
})
var vm = new Vue({
el: '#root'
methods: {
handleClick() {
alert('click')
}
}
})
</script>
2020/2/15大约 2 分钟
Prop 验证
子组件对父组件传递来的参数进行校验
Vue.component('my-component', {
props: {
// 基础的类型检查 (`null` 和 `undefined` 会通过任何类型验证)
propA: Number,
// 多个可能的类型
propB: [String, Number],
// 必填的字符串
propC: {
type: String,
required: true
},
// 带有默认值的数字
propD: {
type: Number,
default: 100
},
// 带有默认值的对象
propE: {
type: Object,
// 对象或数组默认值必须从一个工厂函数获取
default: function () {
return { message: 'hello' }
}
},
// 自定义验证函数
propF: {
validator: function (value) {
// 这个值必须匹配下列字符串中的一个
return ['success', 'warning', 'danger'].indexOf(value) !== -1
}
}
}
})
2020/2/15大约 1 分钟
解析 DOM 模板时的注意事项
<div id="root">
<table>
<tbody>
<row></row>
<row></row>
<row></row>
</tbody>
</table>
</div>
<script type="text/javascript">
Vue.component('row', {
template: '<tr><td>this is a row</td></tr>'
})
var vm = new Vue({
el: '#root'
})
</script>
2020/2/13大约 2 分钟
通过ref
引用调用子组件内的方法并传入参数
父组件:
<子组件标签 ref="refName"></子组件标签>
methods: {
fnX(x) {
this.$refs.refName.fnY(x) // 调用子组件方法并传入值
}
}
2020/2/4小于 1 分钟
子组件1中把值传到父组件,父组件获取值传入子组件2
父组件:
<子组件1 @方法名x="方法名y"></子组件1>
<子组件2 :值名称x="值x"></子组件2 >
data() {
return {
值x: ''
}
},
methods: {
方法名y(值) {
this.值x = 值
}
}
2020/2/4小于 1 分钟