目录
注册组件时候可以不实例化组件对象,直接在注册的时候实例化。{}就是一个组件对象。
- <div id="app">
- <cpn1>cpn1>
- <cpn2>cpn2>
- div>
- <script src="../js/vue.js">script>
- <script>
- // 1.注册全局组件语法糖
- Vue.component('cpn1', {
- template:`
- <div>
- <h2>全局组件语法糖h2>
- <p>全局组件语法糖p>
- div>`
- })
-
- const app = new Vue({
- el:"#app",
- components:{//局部组件创建
- cpn2:{
- template:`
- <div>
- <h2>局部组件语法糖h2>
- <p>局部组件语法糖p>
- div>`
- }
- }
- })
- script>
使用script标签定义组件的模板,script标签注意类型是text/x-template。
-
- <script type="text/x-template" id="cpn1">
- <div>
- <h2>组件模板的分离写法h2>
- <p>script标签注意类型是text/x-templatep>
- div>
- script>
使用template标签,将内容写在标签内。
-
- <template id="cpn2">
- <div>
- <h2>组件模板的分离写法h2>
- <p>template标签p>
- div>
- template>
调用分离的模板,使用template:'#cpn1'
- <script src="../js/vue.js">script>
- <script>
-
- const app = new Vue({
- el: "#app",
- components: { //局部组件创建
- cpn1:{
- template:'#cpn1'
- },
- cpn2: {
- template: '#cpn2'
- }
- }
- })
- script>
前面说过vue组件就是一个vue实例,相应的vue组件也有data属性来存放数据。
在template中使用组件内部的数据msg。
- <div id="app">
- <cpn1>cpn1>
- div>
-
- <script src="../js/vue.js">script>
- <script>
-
- const app = new Vue({
- el: "#app",
- components: { //局部组件创建
- cpn1:{
- template:'{{msg}}',
- data(){
- return {
- msg:"组件的数据存放必须要是一个函数"
- }
- }
- }
- }
- })
- script>
组件的思想是复用,定义组件当然是把通用的公共的东西抽出来复用。
以下代码中定义了两个组件cpn1和cpn2,都是定义了两个计数器,con1的data虽然使用了函数,但是为了模拟data:{count:0},使用了常量obj来返回count。
- <div id="app">
- <h2>data不使用函数h2>
- <cpn1>cpn1>
- <cpn1>cpn1>
- <hr>
- <h2>data使用函数h2>
- <cpn2>cpn2>
- <cpn2>cpn2>
- <hr>
- div>
- <script src="../js/vue.js">script>
- <template id="cpn1">
- <div>
- <button @click="count--">-button>
- 当前计数:{{count}}
- <button @click="count++">+button>
- div>
- template>
- <template id="cpn2">
- <div>
- <button @click="count--">-button>
- 当前计数:{{count}}
- <button @click="count++">+button>
- div>
- template>
- <script>
- const obj = {
- count:0
- };
- const app = new Vue({
- el: "#app",
- components: { //局部组件创建
- cpn1: {
- template: '#cpn1',
- data() {
- return obj;
- }
- },
- cpn2: {
- template: '#cpn2',
- data() {
- return {
- count: 0
- }
- }
- }
- }
- })
- script>

图中可以看到,不使用函数data的好像共用一个count属性,而使用函数的data的count是各自用各自的,像局部变量一样有块级作用域,这个块级就是vue组件的作用域。
我们在复用组件的时候肯定希望,各自组件用各自的变量,如果确实需要都用一样的,可以全局组件注册,也可以是用vuex来进行状态管理。