Vue局部组件如何实现复用,提升项目开发效率?
- 内容介绍
- 文章标签
- 相关推荐
本文共计317个文字,预计阅读时间需要2分钟。
在Vue中,我们可以自定义(注册)局部组件,并指定组件名称:`var ComponentA={ /* ... */ } var ComponentB={ /* ... */ }` 然后在`components`选项中定义你想使用的组件:`new Vue({ el: '...', components: { ComponentA, ComponentB } })`
在Vue中我们可以自己定义(注册)局部组件
定义组件名的方式:
var ComponentA = { /* ... */ } var ComponentB = { /* ... */ }
然后在 components 选项中定义你想要使用的组件:
new Vue({ el: '#app', // 组件中心 components: { // 在视图层渲染 局部注册组件时 // component-a:你要在视图层调用时使用的名称 // ComponentA: 局部注册组件名称 'component-a': ComponentA, 'component-b': ComponentB } })
在视图层调用局部组件:
<div id="app"> <component-a></component-a> <component-b></component-b> </div>
举个列子:
<body> <div id="app"> <component-a></component-a> <component-b></component-b> </div> <script src="./js/vue.js"></script> <script> let componentA = { template:` <p>我是局部组件1</p> ` } let componentB = { template:` <p>我是局部组件2</p> ` } let vm = new Vue({ el:'#app', data:{ }, components:{ "component-a":componentA, "component-b":componentB } }) </script>
输出结果为:
本文共计317个文字,预计阅读时间需要2分钟。
在Vue中,我们可以自定义(注册)局部组件,并指定组件名称:`var ComponentA={ /* ... */ } var ComponentB={ /* ... */ }` 然后在`components`选项中定义你想使用的组件:`new Vue({ el: '...', components: { ComponentA, ComponentB } })`
在Vue中我们可以自己定义(注册)局部组件
定义组件名的方式:
var ComponentA = { /* ... */ } var ComponentB = { /* ... */ }
然后在 components 选项中定义你想要使用的组件:
new Vue({ el: '#app', // 组件中心 components: { // 在视图层渲染 局部注册组件时 // component-a:你要在视图层调用时使用的名称 // ComponentA: 局部注册组件名称 'component-a': ComponentA, 'component-b': ComponentB } })
在视图层调用局部组件:
<div id="app"> <component-a></component-a> <component-b></component-b> </div>
举个列子:
<body> <div id="app"> <component-a></component-a> <component-b></component-b> </div> <script src="./js/vue.js"></script> <script> let componentA = { template:` <p>我是局部组件1</p> ` } let componentB = { template:` <p>我是局部组件2</p> ` } let vm = new Vue({ el:'#app', data:{ }, components:{ "component-a":componentA, "component-b":componentB } }) </script>
输出结果为:

