在 Vue 中,使用了基於HMTL的模板,这种模板与允许开发者声明式地将 DOM 绑定至底层 Vue 实例的数据。所有 Vue.js 的模板都是合法的 HTML,所以能被遵循规范的浏览器和 HTML 解析器解析。
在底层的实现上,Vue 会将模板编译成渲染函数,而渲染函数则会因响应系统的触发而重新渲染页面。
而要如何在 Vue 上进行数据绑定呢? 在Vue中需使用 {{ }}(双大括号)的形式告诉 Vue 你要将文本与谁进行绑定。
可以透过以下Grant预先键好的sandbox看看效果:
https://codesandbox.io/s/muddy-dust-hj5oy?file=/src/App.vue
<template>
<div id="app">
<span>Message: {{ msg }}</span>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
msg: "Hi, this is Grant.",
};
},
};
</script>
结果显示如下:
若使用 Vue 框架开发时,要绑定 HTML 元素上的属性(attribute)时,就要搭配 v-bind 来使用。
以 HTML 元素的 title 属性作为范例,title 属性的效果,就是当游标停留在 HTML 元素时,会跳出提示。
如下面的程序码所示,我们将变数hint绑定在button之上,当经过渲染後,变数就会被绑定至button的title上。
<template>
<div id="app">
<span>Message: {{ msg }}</span
><br /><br />
<button v-bind:title="hint">Click me !</button>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
msg: "Hi, this is Grant.",
hint: "hey! click me",
};
},
};
</script
<template>
<div id="app">
<span>Message: {{ msg }}</span
><br /><br />
<button :class="title" :title="hint">Click me !</button>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
msg: "Hi, this is Grant.",
hint: "hey! click me",
title: "title",
};
},
};
</script>
<style>
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.title {
color: #c995F2;
}
</style>
v-model 是绑定在表单元件或自订元件上,为实现双向绑定用的。表单元件像是"input"、"select"和"textarea"等等。
<template>
<div id="app">
<input type="text" v-model="message" /><br><br>
<span>{{ message }}</span>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
message: "Hello World!"
};
},
};
让我们来看一下效果~
上述程序码中我们建立一个input box,以及一个span的tag,在input box上我们将之与message进行绑定,并在span上显示message变数的内容。
现在就来看一下双向绑定的效果~
当修改textbox中的文字内容,span中的内容也随之更新,是不是很神奇呢!
以上就是Vue的资料绑定与模板语法,明天见罗~
二元搜寻树(Binary Search Tree)建立的方法 insert: 新增元素进入树中 de...
前言 前面几天谈的都是纯文字的资料验证,像是信箱、电话等等,但很多 API server 除了文字资...
前面 [day-5] 有基本介绍Hello World的用途 在我们正式开始写程序之前,先来认识一下...
在使用面板成功备份还原後, 再使用SSMS实作的可行性, 是否跟地端的一样? 先使用UI方式备份, ...
昨天用 Vite 快速打造了输入信箱获取认证码的页面,但必须搭配发送认证码的 API 才能继续完成这...