组件
- 记住全局注册的行为必须在根 Vue 实例创建 (new Vue) 之前发生。
- 当使用 kebab-case (短横线分隔命名) 定义一个组件时,你也必须在引用这个自定义元素时使用 kebab-case,例如
<my-component-name>
全局注册
- 当你使用 Vue.component 全局注册一个组件时,这个全局的 ID 会自动设置为该组件的 name 选项。
Vue.component('unique-name-of-my-component', {...})
局部注册
new Vue({
el: '#transition-components-demo',
data: {
view: 'v-a'
},
components: {
'v-a': {
template: '<div>Component A</div>'
},
'v-b': {
template: '<div>Component B</div>'
}
}
})
同步注册组件
Vue.component('custom-input', {
props: ['value'],
template: `
<input
v-bind:value="value"
v-on:input="$emit('input', $event.target.value)" // $event.target指向时间对象,input对象有value属性
>
`
})
异步注册组件
Vue.component(
'async-webpack-example',
// 这个 `import` 函数会返回一个 `Promise` 对象。
() => import('./my-async-component') // import(...)基于ES6,返回Promise对象,当对象返回成功后调用解析。webpack会把这个异步加载的模块单独打包,可以通过注释来配置打包的名称及方法。
)
// 或者
new Vue({
// ...
components: {
'my-component': () => import('./my-async-component')
}
})
- Vue 允许你以一个工厂函数的方式定义你的组件,这个工厂函数会异步解析你的组件定义。Vue 只有在这个组件需要被渲染的时候才会触发该工厂函数,且会把结果缓存起来供未来重渲染。
Vue.component('async-example', function (resolve, reject) {
setTimeout(function () {
// 向 `resolve` 回调传递组件定义
resolve({ // 加载完成,触发解析
template: '<div>I am async!</div>'
})
}, 1000)
})
- 还可以在工厂函数中返回一个对象(如果你希望在 Vue Router 的路由组件中使用上述语法的话,你必须使用 Vue Router 2.4.0+ 版本)
const AsyncComponent = () => ({
// 需要加载的组件 (应该是一个 `Promise` 对象)
component: import('./MyComponent.vue'),
// 异步组件加载时使用的组件
loading: LoadingComponent,
// 加载失败时使用的组件
error: ErrorComponent,
// 展示加载时组件的延时时间。默认值是 200 (毫秒)
delay: 200,
// 如果提供了超时时间且组件加载也超时了,
// 则使用加载失败时使用的组件。默认值是:`Infinity`
timeout: 3000
})
两个组件互相引用时
- 两个组件互相引用时,通过 Vue.component 全局注册组件的时候,这个悖论会被自动解开。
- 局部注册时,可以在beforeCreate中修改初始化选项,避免解析组件的死循环
beforeCreate: function () {
this.$options.components.TreeFolderContents = require('./tree-folder-contents.vue').default // require该方法来源于nodejs,建议用import from代替
}
——————————————————————————————————————————————
插件
Vue.use
- 通过全局方法 Vue.use() 使用插件。它需要在你调用 new Vue() 启动应用之前完成:可以传入一个选项对象:
// 调用 `MyPlugin.install(Vue)`
Vue.use(MyPlugin, { someOption: true })
new Vue({
//... options
})
- Vue.js 的插件应该有一个公开方法 install。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象:
MyPlugin.install = function (Vue, options) {
// 1. 添加全局方法或属性,例如:data,computed等
Vue.myGlobalMethod = function () {
// 逻辑...
}
// 2. 添加全局资源,例如v-table等
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 逻辑...
}
...
})
// 3. 注入组件,混入
Vue.mixin({
created: function () {
// 逻辑...
}
...
})
// 4. 添加实例方法,例如vm.$on等
Vue.prototype.$myMethod = function (methodOptions) {
// 逻辑...
}
}