声明式渲染
文本插值,模板语法:
<div id="counter">
Counter: {{ counter }}
</div>
const Counter = {
data() {
return {
counter: 0
}
}
}
Vue.createApp(Counter).mount('#counter')
const CounterApp = {
data() {
return {
counter: 0
}
},
mounted() {
setInterval(() => {
this.counter++
}, 1000)
}
}
绑定元素属性:
<div id="bind-attribute">
<span v-bind:title="message">
Hover your mouse over me for a few seconds to see my dynamically bound
title!
</span>
</div>
const AttributeBinding = {
data() {
return {
message: 'You loaded this page on ' + new Date().toLocaleString()
}
}
}
Vue.createApp(AttributeBinding).mount('#bind-attribute')
处理用户输入
v-on指令,事件侦听:
<div id="event-handling">
<p>{{ message }}</p>
<button v-on:click="reverseMessage">Reverse Message</button>
</div>
const EventHandling = {
data() {
return {
message: 'Hello Vue.js!'
}
},
methods: {
reverseMessage() {
this.message = this.message
.split('')
.reverse()
.join('')
}
}
}
Vue.createApp(EventHandling).mount('#event-handling')
v-model指令,双向绑定:
<div id="two-way-binding">
<p>{{ message }}</p>
<input v-model="message" />
</div>
const TwoWayBinding = {
data() {
return {
message: 'Hello Vue!'
}
}
}
Vue.createApp(TwoWayBinding).mount('#two-way-binding')
条件和循环
v-if指令,切换元素的存在:
<div id="conditional-rendering">
<span v-if="seen">Now you see me</span>
</div>
const ConditionalRendering = {
data() {
return {
seen: true
}
}
}
Vue.createApp(ConditionalRendering).mount('#conditional-rendering')
v-for指令,循环元素:
<div id="list-rendering">
<ol>
<li v-for="todo in todos">
{{ todo.text }}
</li>
</ol>
</div>
const ListRendering = {
data() {
return {
todos: [
{ text: 'Learn JavaScript' },
{ text: 'Learn Vue' },
{ text: 'Build something awesome' }
]
}
}
}
Vue.createApp(ListRendering).mount('#list-rendering')
组成组件
注册组件:
// Create Vue application
const app = Vue.createApp(...)
// Define a new component called todo-item
app.component('todo-item', {
template: `<li>This is a todo</li>`
})
// Mount Vue application
app.mount(...)
使用:
<ol>
<!-- Create an instance of the todo-item component -->
<todo-item></todo-item>
</ol>
属性:
app.component('todo-item', {
props: ['todo'],
template: `<li>{{ todo.text }}</li>`
})
使用:
<div id="todo-list-app">
<ol>
<!--
Now we provide each todo-item with the todo object
it's representing, so that its content can be dynamic.
We also need to provide each component with a "key",
which will be explained later.
-->
<todo-item
v-for="item in groceryList"
v-bind:todo="item"
v-bind:key="item.id"
></todo-item>
</ol>
</div>
const TodoList = {
data() {
return {
groceryList: [
{ id: 0, text: 'Vegetables' },
{ id: 1, text: 'Cheese' },
{ id: 2, text: 'Whatever else humans are supposed to eat' }
]
}
}
}
const app = Vue.createApp(TodoList)
app.component('todo-item', {
props: ['todo'],
template: `<li>{{ todo.text }}</li>`
})
app.mount('#todo-list-app')