Vuejs template快速入门

一直想写一个Vuejs的系列的博客,苦于一直没有时间,今天的这个博客也是思考了很久,打算随便写点东西,今天说说Vuejs的模版的使用。

Vue模版的使用方法

  1. 直接用Html

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

    <div id="container">
    <mytemp></mytemp>
    </div>

    <script src="vue.min.js"></script>
    <script>
    Vue.component('mytemp', {
    template: ' <h1>Hello I am Temple</h1>',

    })
    new Vue().$mount("#container");

    </script>

  2. 使用标签

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17

    <div id="container">
    <mytemp></mytemp>
    </div>
    <script id="temp1" type="x-template">
    <h1>Hello I am Temple</h1>
    </script>
    <script src="vue.min.js"></script>
    <script>
    Vue.component('mytemp', {
    template: '#temp1'
    })
    new Vue().$mount("#container");

    </script>


  3. 使用template标签

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16

    <div id="container">
    <mytemp></mytemp>
    </div>
    <template id="temp1">
    <h1>Hello I am Temple</h1>
    </template>
    <script src="vue.min.js"></script>
    <script>
    Vue.component('mytemp', {
    template: '#temp1'
    })
    new Vue().$mount("#container");

    </script>

局部模版

上面我们使用的全局模版,这个模版可以在所有的vue对象中使用,如果我们仅仅想让在当前的vue中生效,就要用局部的模版注册

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 <div id="container">
<mytemp></mytemp>
</div>
<template id="temp1">
<h1>Hello I am Temple</h1>
</template>
<script src="vue.min.js"></script>
<script>
new Vue({
components: {
'mytemp': {
template: '#temp1'
}
}
}).$mount("#container");

</script>

模版的传值


单项传递

对于我们的传值,我们可以看成父模版向子模版传值,其中vue是父对象,template是子对象,这里我们需要使用props属性,修改我们的额demo如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<div id="container">
<mytemp v-bind:myname="name"></mytemp>
</div>
<template id="temp1">
<h1>Hello I am {{myname}} Temple</h1>
</template>
<script src="vue.min.js"></script>
<script>
new Vue({
data: {
name: "Vue"
},
components: {
'mytemp': {
template: '#temp1',
props: ["myname"]
}
}
}).$mount("#container");

</script>

注意:props这里尽量使用小写字段,驼峰命名需要转化成-

双向传递

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<div id="container">
<mytemp v-bind:myname.sync="name"></mytemp>
<h1>{{name}}</h1>
</div>
<template id="temp1">
<input type="" name="" v-model="myname" /> {{myname}}
</template>
<script src="vue.min.js"></script>
<script>
new Vue({
data: {
name: "Vue"
},
components: {
'mytemp': {
template: '#temp1',
props: ["myname"]
}
}
}).$mount("#container");

</script>

参考资料:Vue.js——60分钟组件快速入门(上篇)

作者

付威

发布于

2018-01-10

更新于

2020-08-10

许可协议

评论