小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
数据绑定
第一次接触到数据绑定概念,还是在 Angularjs 1.x 时候,Angularjs 1.x 出现让我们习惯了 JQuery 的前端开发者耳目一新,可以说一次飞跃,随后有机会根大家聊一聊 MVVM 设计模式,其实这种设计模式并没有什么新意,多年前微软就在桌面应用开发中就提出了这种设计模式,只不过这个现在有人将他引入到 web 开发中,并且盛行一时。有时候说明多学一些没有什么坏处,突破局限不仅要靠内力,有时候也需要跨界的灵感。
- 双向绑定
- 渲染方法
- 事件绑定
今天我们主要介绍的是渲染方法,也可以理解为单向绑定,所谓单向绑定就是将数据集,也就是将数据绑定到 UI 上,当数据发生改变了,界面上也会随着数据发生变化。
| 指令名称 | 指令说明 | |
|---|---|---|
| v-text | 将文本绑定到 html 元素上,这个应该是一个单向绑定 | |
| v-html | 将 html 结构文本绑定 HTML 元素上 | |
| v-bind | 将变量绑定到 HTML 属性上,例如 v-bind:class 或者 v-bind:style | |
今天主要介绍
绑定文本
今天介绍如何将 script 代码块中数据绑定到到 template 的 UI 上,我们把 hello-world 项目中 components 中 HelloWorld 组件去掉,让项目变得比较干净这样一来便于关注要学习内容。
<template>
<h1>Hello Vue</h1>
</template>
<script>
export default {
name: 'App',
}
</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;
}
</style>
在 Vue 数据绑定遵循 mustache 语法,大家可以了解一个 mustache 一些,对于一些小的项目或者比较鼓励项目可以引入 mustache 来实现数据绑定,早在之前自己就用用 mustache 实现过数据绑定。在大括号之间仅支持表达式,并不支持声明语句,有关数据复杂操作交个 vue 来处理。
<template>
<h1>{{title}}</h1>
</template>
<script>
export default {
name: 'App',
data(){
return {
title:"machine learning"
}
}
}
</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;
}
</style>
在花括号也支持一些运算操作,
<template>
<h1>title: {{title}}</h1>
<h1>lessons: {{ 2 + 5 }}</h1>
</template>
指令集方式来绑定文本
在 Vue 提供另一种方式,用指令集方式来将文本绑定到页面上 DOM 元素,在 Vue 中指令集都是 v 加连接符方式的指令集。
<template>
<h1>title: {{title}}</h1>
<h1>lessons: {{ 2 + 5 }}</h1>
<h1 v-text="subTitle"></h1>
</template>
<template>
<h1>title: {{title}}</h1>
<h1>lessons: {{ 2 + 5 }}</h1>
<h1 v-text="subTitle">hello</h1>
</template>
VueCompilerError: v-text will override element children.
at /Users/zidea2020/Desktop/myrepo/vue_tut/hello-world/src/App.vue:4:5
2 | <h1>title: {{title}}</h1>
3 | <h1>lessons: {{ 2 + 5 }}</h1>
4 | <h1 v-text="subTitle">hello</h1>
| ^^^^^^^^^^^^^^^^^
5 | </template>
6 |
绑定 HTML
想要将 html 绑定到界面上,也就是将带有 html 标签结构的字符串渲染到界面上,需要对 html 语义进行解析功能,这里采用了 v-html来解析字符串。
<script>
export default {
name: 'App',
data(){
return {
title:"machine learning",
subTitle:"<b>regression</b>"
}
}
}
</script>
v-text 无法将带有 html 标签字符串进行解析后渲染到界面上。
<template>
<h1>title: {{title}}</h1>
<h1>lessons: {{ 2 + 5 }}</h1>
<div v-text="subTitle"></div>
</template>
<template>
<h1>title: {{title}}</h1>
<h1>lessons: {{ 2 + 5 }}</h1>
<div v-html="subTitle"></div>
</template>
通过 v-html 绑定就可以去解析 html 标签然后将文本渲染到界面上。
<template>
<h1>title: {{title}}</h1>
<h1>lessons: {{ 2 + 5 }}</h1>
<div v-html="subTitle"></div>
<div v-html="moreInfo"></div>
</template>
<script>
export default {
name: 'App',
data(){
return {
title:"machine learning",
subTitle:"<b>regression</b>",
moreInfo: `<a href="#" onclick="alert('machine learning regression')" >more info</a>`
}
}
}
</script>