vue-笔记201803


全局注册
我们已经知道,可以通过以下方式创建一个 Vue 实例:

new Vue({
el: '#some-element',
// 选项
})
要注册一个全局组件,可以使用 Vue.component(tagName, options)。例如:
挂载在Vue上的为全局
Vue.component('my-component', {
// 选项
})

局部注册
你不必把每个组件都注册到全局。你可以通过某个 Vue 实例/组件的实例选项 components 注册仅在其作用域中可用的组件:

var Child = {
template: '<div>A custom component!</div>'
}

new Vue({
// ...
components: {
// <my-component> 将只在父组件模板中可用
'my-component': Child
}
})
这种封装也适用于其它可注册的 Vue 功能,比如指令。


组件实例的作用域是孤立的。这意味着不能 (也不应该) 在子组件的模板内直接引用父组件的数据。父组件的数据需要通过 prop 才能下发到子组件中。

子组件要显式地用 props 选项声明它预期的数据:

Vue.component('child', {
// 声明 props
props: ['message'],
// 就像 data 一样,prop 也可以在模板中使用
// 同样也可以在 vm 实例中通过 this.message 来使用
template: '<span>{{ message }}</span>'
})
然后我们可以这样向它传入一个普通字符串:

<child message="hello!"></child>
结果:

原文地址:https://www.cnblogs.com/lizhibk/p/8623595.html