1. Interpolación
Interpolación: utilice llaves dobles { {}} para vincular datos a la plantilla para lograr una representación de datos simple. Por ejemplo: <p>{ {mensaje}}</p>, donde mensaje es una variable.
1.1.3 Propiedades
Los valores en los atributos HTML deben usar la directiva v-bind
1.1.4 Expresiones
1.1.1 Texto
{ {mensaje}
1.1.2 HTML
Utilice v-html
Vue proporciona soporte completo para expresiones JavaScript
El efecto es el siguiente:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>入门</title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<style type="text/css">
.f30{
font-size: 30px;
}
</style>
</head>
<body>
<div id="app">
{
{msg}}
<p>html解析</p>
{
{msg2}}
<b :class="msg3" v-html="msg2"></b>
{
{msg4+1}}
{
{sb.substring(3,8)}}
<input v-model="ok">
{
{ok==1? "你好我是雪豹":"妈妈每天都给我抽点支烟,以及听雪"}}
</div>
<script type="text/javascript">
new Vue({
el:"#app",
data(){
return {msg:'hellow 你好 vue',
msg2:'<span style="color:yellow">hello 你好vue </span>',
msg3:'f30',
msg4:5,
ok:1,
sb:'邓郑伟学坤坤跳舞'
}
}
})
</script>
</body>
</html>
2. Instrucciones:
Usando atributos especiales que comienzan con v-, puede implementar operaciones DOM, representación condicional, bucles, enlace de eventos y otras funciones. Por ejemplo: <p v-if="isShow">{ {message}}</p>, donde v-if es una instrucción de representación condicional.
instrucciones básicas
(v-si|v-else|v-else-if)/v-show/v-for/v-bind/v-on/v-modelo
v-if|v-else|v-else-if: determina si se representa el elemento en función del valor bool de la expresión posterior
Sólo pueden ser elementos hermanos.
El elemento hermano anterior de v-else-if debe ser v-if
El elemento hermano anterior de v-else debe ser v-if o v-else-if
v-show: similar a v-if, excepto que representará elementos cuya expresión detrás de ellos sea falsa y agregará código CSS a dichos elementos: style="display:none"
v-for: recorrido tipo JS,
Recorre la matriz: v-for = "elemento en elementos", elementos es una matriz, elemento es un elemento de matriz en la matriz
Recorrer objetos: v-for="(valor, clave, índice) en stu", valor del atributo de valor, nombre del atributo clave, subíndice de índice
enlace v
v-encendido
v-model: se utiliza para crear un enlace de datos bidireccional en elementos de control de formulario como entrada, selección, área de texto, casilla de verificación, radio, etc., y actualiza automáticamente el valor del elemento enlazado según el valor del formulario.
v-for/v-model une las casillas de verificación [selección múltiple] y los botones de opción
usar:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<title>指令</title>
</head>
<body>
<div id="app">
<input v-model="score">
<b v-if="score < 60 ">不及格</b>
<b v-else-if="score >= 60 && score <70 ">及格</b>
<b v-else-if="score >= 70 && score <80 ">中等</b>
<b v-else-if="score >= 80 && score <90 ">良好</b>
<b v-else="score >=90 && score <100>">优秀</b>
<b>{
{array}}</b>
<i v-for="a in array">{
{a}}||</i>
<i v-for="u in User">{
{u.name}}喜欢{
{u.hobby}}今年{
{u.age}}</i>
<br />
<select>
<option v-for="h in hobby" :value="h.id">
{
{h.name}}
</option></select>
<br />
<div v-for="h in hobby"><input type="checkbox" name="hpbby" :value="h.id">{
{h.name}}</div>
<p>v-show</p>
<div v-show="score>90">v-show-上优秀学员名单</div>
<div v-if="score>90">v-if-上优秀学员名单</div>
</div>
<script type="text/javascript">
new Vue({
el:'#app',
data(){
return {score:60,
array:[1,2,3,4],
User:[{name:'小威',hobby:'玩棒子',age:18},
{name:'小威',hobby:'玩棒子',age:18},
{name:'小威',hobby:'玩棒子',age:18}],
hobby:[{id:1,name:'洗脚'},
{id:2,name:'保健'},
{id:3,name:'按摩'},
{id:4,name:'spa'}]
}
}
})
</script>
</body>
</html>
Efecto:
3.Parámetros dinámicos
Parámetros dinámicos: además de utilizar nombres de instrucciones fijos, los parámetros dinámicos también se pueden utilizar para vincular datos dinámicamente. Por ejemplo: <a v-bind:href="url">{ { message }}</a>, donde v-bind vincula dinámicamente el valor del atributo href.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<title>指令</title>
</head>
<body>
<div id="app">
<input v-model="score">
<b v-if="score < 60 ">不及格</b>
<b v-else-if="score >= 60 && score <70 ">及格</b>
<b v-else-if="score >= 70 && score <80 ">中等</b>
<b v-else-if="score >= 80 && score <90 ">良好</b>
<b v-else="score >=90 && score <100>">优秀</b>
<b>{
{array}}</b>
<i v-for="a in array">{
{a}}||</i>
<i v-for="u in User">{
{u.name}}喜欢{
{u.hobby}}今年{
{u.age}}</i>
<br />
<select>
<option v-for="h in hobby" :value="h.id">
{
{h.name}}
</option></select>
<br />
<div v-for="h in hobby"><input type="checkbox" name="hpbby" :value="h.id">{
{h.name}}</div>
<p>v-show</p>
<div v-show="score>90">v-show-上优秀学员名单</div>
<div v-if="score>90">v-if-上优秀学员名单</div>
<p>动态参数</p>
<input v-model="evname"/>
<button v-on:[evname]="test">点我</button>
</div>
<script type="text/javascript">
new Vue({
el:'#app',
data(){
return {score:60,
array:[1,2,3,4],
User:[{name:'小威',hobby:'玩棒子',age:18},
{name:'小威',hobby:'玩棒子',age:18},
{name:'小威',hobby:'玩棒子',age:18}],
hobby:[{id:1,name:'洗脚'},
{id:2,name:'保健'},
{id:3,name:'按摩'},
{id:4,name:'spa'}],
evname:'click'
};
}
,methods:{
test(){
alert("点我试试")
}
}
})
</script>
</body>
</html>
4.Filtro
Vue permite filtros personalizados, generalmente utilizados para el formato de texto común. Los filtros están disponibles en dos lugares: interpolación de doble llave y expresiones v-bind . Los filtros deben agregarse al final de las expresiones js, usando operaciones de canalización. Símbolo " | "
filtro local
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<title>过滤器</title>
</head>
<body>
<div id='app'>
<p>局部过滤器</p>
{
{msg}}
<p>局部过滤器串行使用</p>
{
{msg | filterA | filterB}}
<p>局部过滤器传参</p>
{
{msg | filterC(2,5)}}
</div>
<script type="text/javascript">
new Vue({
el:'#app',
filters:{
'filterA':function(v){
return v.substring(0,5);
},
'filterB':function(v){
return v.substring(2,5);
},
'filterC':function(v,begin,end){
return v.substring(begin,end);
}
},
data(){
return {
msg:'你好 饿了么'
}
}
})
</script>
</body>
</html>
filtro global
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="date.js"></script>
<title>过滤器</title>
</head>
<body>
<div id='app'>
<p>局部过滤器</p>
{
{msg}}
<p>局部过滤器串行使用</p>
{
{msg | filterA | filterB}}
<p>局部过滤器传参</p>
{
{msg | filterC(2,5)}}
<p>全局过滤器</p>
没有过滤器的结果: {
{time}}
有过滤器的结果:{
{time|fmtDate}}
<script src="js/date.js"></script>
</div>
<script type="text/javascript">
Vue.filter('fmtDate', function(value) {
return fmtDate(value, 'yyyy年MM月dd日')
});
new Vue({
el:'#app',
filters:{
'filterA':function(v){
return v.substring(0,5);
},
'filterB':function(v){
return v.substring(2,5);
},
'filterC':function(v,begin,end){
return v.substring(begin,end);
}
},
data(){
return {
msg:'你好 饿了么',
time:new Date()
}
}
})
</script>
</body>
</html>
datos.js
//给Date类添加了一个新的实例方法format
Date.prototype.format = function (fmt) {
//debugger;
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
};
function fmtDate(date, pattern) {
var ts = date.getTime();
var d = new Date(ts).format("yyyy-MM-dd hh:mm:ss");
if (pattern) {
d = new Date(ts).format(pattern);
}
return d.toLocaleString();
};
resultado:
5. Propiedades calculadas y propiedades de seguimiento.
Propiedades calculadas
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<meta charset="utf-8">
<title>计算属性监听属性</title>
</head>
<body>
<div id="app">
<p>计算属性</p>
单价:<input v-model="price">
数量:<input v-model="num">
小计:{
{count}}
</div>
<script type="text/javascript">
new Vue({
el:'#app',
data(){
return {
price:79,
num:1
};
},
computed:{
count:function(){
return this.price*this.num
}
}
})
</script>
</body>
</html>
Efecto:
Cambiar a 2
Características de los atributos calculados: una parte afecta a la otra (unidireccional)
Propiedades auditivas:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<meta charset="utf-8">
<title>计算属性监听属性</title>
</head>
<body>
<div id="app">
<p>计算属性</p>
单价:<input v-model="price">
数量:<input v-model="num">
小计:{
{count}}
<p>监听属性</p>
千米:<input v-model="km" />
米:<input v-model="m"/>
</div>
<script type="text/javascript">
new Vue({
el:'#app',
data(){
return {
price:79,
num:1,
m:1000,
km:1
};
},
computed:{
count:function(){
return this.price*this.num
}
},
watch:{
km:function(v){
this.m=parseInt(v) * 1000;
},
m:function(v){
this.km=parseInt(v) / 1000;
}
}
})
</script>
</body>
</html>
Efecto:
Características de los atributos de seguimiento: dos partes se influyen entre sí (bidireccional)
Caso práctico:
carro de la compra:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>购物车</title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.10/vue.js"></script>
<style>
.container {
width: 600px;
margin: 0 auto;
}
table {
border-collapse: collapse;
width: 100%;
}
table td {
border: 1px solid #ddd;
padding: 10px;
text-align: center;
}
.input-wrapper {
display: flex;
justify-content: center;
align-items: center;
}
button {
padding: 5px 10px;
background-color: #eee;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<div id="app" class="container">
<p>购物车</p>
<table>
<thead>
<tr>
<th>物品</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in items" :key="index">
<td>{
{ item.name }}</td>
<td>{
{ item.price }}</td>
<td class="input-wrapper">
<button @click="decrement(index)">-</button>
<input v-model="item.quantity" />
<button @click="increment(index)">+</button>
</td>
<td>{
{ item.price * item.quantity }}</td>
</tr>
<tr>
<td colspan="3">总价</td>
<td>{
{ total }}</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
new Vue({
el: '#app',
data() {
return {
items: [
{ name: '帽子', price: 10, quantity: 1 },
{ name: '衣服', price: 30, quantity: 1 },
{ name: '裤子', price: 20, quantity: 1 },
{ name: '肾宝片', price: 200, quantity: 1 },
{ name: '羊腰子', price: 20, quantity: 1 },
],
};
},
methods: {
increment(index) {
this.items[index].quantity++;
},
decrement(index) {
if (this.items[index].quantity > 1) {
this.items[index].quantity--;
}
},
},
computed: {
total() {
return this.items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
},
},
});
</script>
</body>
</html>
Efecto: