版权声明:Myfour的个人笔记 转载请声明来源 https://blog.csdn.net/sinat_36663351/article/details/85161834
Vue.js组件
- 所有组件需要在初始化根实例前注册
// 注册 Vue.component('my-component', { template: '<div>A custom component!</div>' }) // 创建根实例 new Vue({ el: '#example' })
- 组件作用域
- 全局与局部
- 全局组件:
Vue.component(tagName, options)
- 局部组件,在一个Vue实例中设置components属性
new Vue({ // ... components: { // <my-component> 将只在父组件模板中可用 'my-component': Child } })
- 组件中的data属性必须是一个function
Vue.component('simple-counter', { template: '<button v-on:click="counter += 1">{{ counter }}</button>', // 技术上 data 的确是一个函数了,因此 Vue 不会警告, // 但是我们却给每个组件实例返回了同一个对象的引用 data: function () { return { a:1, b:2 } } })
组件间的数据传输
- 父子组件的关系可以总结为 prop 向下传递,事件向上传递
- 父组件通过 prop 给子组件下发数据,子组件通过事件给父组件发送消息
Vue.component('child', { // 声明 props props: ['message'], // 就像 data 一样,prop 也可以在模板中使用 // 同样也可以在 vm 实例中通过 this.message 来使用 template: '<span>{{ message }}</span>' })
- 通过为元素传入props中定义的属性值来传数据
<child message="hello!"></child>
- 子组件与父组件传数据,通过子组件往父组件触发事件来传递数据
Vue.component('balance', { template: ` <div> <show @show-balance='show_balance'></show> <div v-if='show'> 显示余额:$100,000,000 </div> </div> `, // 父组件中的子组件元素中为触发的show-balance事件触发方法,传入方法名 在 触发的方法中通过形参就可以获取字组件传来的数据对象 data: function () { return { show: false } }, methods: { show_balance: function (data) { this.show = true console.log(data) } } }) Vue.component('show', { template: '<button @click="on_click()">显示余额</button>', // 点击触发一个方法,该方法发送一个show-balance事件到父组件中, // 同时传入数据对象 methods: { on_click: function () { this.$emit('show-balance', { a: 1, b: 2 }) } } }) var app = new Vue({ el: '#app', })