2.Vue入门

2.Vue入门

声明式渲染

{{...}} : 文本插入

1
2
3
4
5
6
7
8
9
10
11
<body>
<div id='app'>{{message}}</div>
</body>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello Vue'
}
})
</script>

数据和 DOM 已经被建立了关联,所有东西都是响应式的

指令

指令带有前缀 v-,以表示它们是 Vue 提供的特殊 Attribute

绑定

v-bind:title : 将元素的 title 和 Vue 实例的 message 绑定起来

1
2
3
4
5
6
7
8
9
10
11
12
13
<body>
<div id="app2">
<span v-bind:title='message'>动态绑定的信息</span>
</div>
</body>
<script>
new Vue({
el: '#app2',
data: {
message: '页面加载与' + new Date().toLocaleString()
}
})
</script>
条件

v-if : 条件控制,当Vue 实例的seen为true时显示元素

1
2
3
4
5
6
7
8
9
10
11
12
13
<body>
<div id="app3">
<p v-if="seen">aaaaaaa</p>
</div>
</body>
<script>
new Vue({
el: '#app3',
data: {
seen: true
},
})
</script>
循环

v-for : 遍历Vue中绑定的数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<body>
<div id="app4">
<ol>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ol>
</div>
</body>
<script>
new Vue({
el: '#app4',
data: {
todos: [
{ text: 'a' },
{ text: 'b' },
{ text: 'c' }
]
}
})
</script>
事件监听

v-on添加事件监听器

v-on:click : 添加单击事件监听

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<body>		
<div id="app5">
<p>{{ message }}</p>
<button v-on:click="reverseMessage">反转消息</button>
</div>
</body>
<script>
new Vue({
el: '#app5',
data: {
message: 'Hello Vue'
},
methods: {
reverseMessage: function() {
this.message = this.message.split('').reverse().join('')
}
},
})
</script>

v-model : 将输入框和Vue中实例绑定起来

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<body>
<div id="app6">
<p>{{ message }}</p>
<input v-model="message">
</div>
</body>
<script>
new Vue({
el: '#app6',
data: {
message: 'Hello'
}
})
</script>

2.Vue入门
http://xwww12.github.io/2022/07/29/前端/vue/2.Vue入门/
作者
xw
发布于
2022年7月29日
许可协议