表单输入绑定
<!-- 文本 (Text) -->
<input v-model="message" placeholder="edit me" />
<p>Message is: {{ message }}</p>
<!-- 多行文本 (Textarea) -->
<textarea v-model="message" placeholder="add multiple lines"></textarea>
<!-- 复选框 (Checkbox) -->
<input type="checkbox" id="checkbox" v-model="checked" />
<div id="v-model-multiple-checkboxes">
<input type="checkbox" id="jack" value="Jack" v-model="checkedNames" />
<label for="jack">Jack</label>
<input type="checkbox" id="john" value="John" v-model="checkedNames" />
<label for="john">John</label>
<input type="checkbox" id="mike" value="Mike" v-model="checkedNames" />
<label for="mike">Mike</label>
<span>Checked names: {{ checkedNames }}</span>
</div>
<!-- 单选框 (Radio) -->
<div id="v-model-radiobutton">
<input type="radio" id="one" value="One" v-model="picked" />
<label for="one">One</label>
<br />
<input type="radio" id="two" value="Two" v-model="picked" />
<label for="two">Two</label>
<span>Picked: {{ picked }}</span>
</div>
<!-- 当选中时 vm.pick === vm.a -->
<input type="radio" v-model="pick" v-bind:value="a" />
<!-- 选择框 (Select) -->
<div id="v-model-select" class="demo">
<select v-model="selected">
<option disabled value="">Please select one</option>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<span>Selected: {{ selected }}</span>
</div>
<select v-model="selected" multiple>
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<span>Selected: {{ selected }}</span>
<!-- 内联对象字面量 当选中时 typeof vm.selected => 'object' vm.selected.number => 123 -->
<select v-model="selected">
<option :value="{ number: 123 }">123</option>
</select>
<!-- 修饰符 -->
<!-- 在“change”时而非“input”时更新 -->
<input v-model.lazy="msg" />
<!-- 自动将用户的输入值转为数值类型 -->
<input v-model.number="age" type="text" />
<!-- 自动过滤用户输入的首尾空白字符 -->
<input v-model.trim="msg" />
组件基础
两种组件的注册类型:全局注册和局部注册。通过 component 方法全局注册。
// 创建一个Vue 应用
const app = Vue.createApp({})
// 定义一个名为 button-counter 的新全局组件
app.component('button-counter', {
data() {
return {
count: 0
}
},
template: `
<button @click="count++">
You clicked me {{ count }} times.
</button>`
})
<!-- 通过 Prop 向子组件传递数据 -->
<div id="blog-post-demo" class="demo">
<blog-post title="My journey with Vue"></blog-post>
<blog-post title="Blogging with Vue"></blog-post>
<blog-post title="Why Vue is so fun"></blog-post>
</div>
<script>
app.component("blog-post", {
props: ["title"],
template: `<h4>{{ title }}</h4>`,
});
</script>
<!-- 子组件可以通过调用内建的 $emit 方法并传入事件名称来触发一个事件 -->
<blog-post v-for="post in posts" :key="post.id" :title="post.title" @enlarge-text="postFontSize += 0.1"></blog-post>
<script>
app.component("blog-post", {
props: ["title"],
template: `
<div class="blog-post">
<h4>{{ title }}</h4>
<button @click="$emit('enlargeText')">
Enlarge text
</button>
</div>
`,
});
</script>