<div id="counter"><p>{{num}}</p><p>{{uname}}</p></div>
const Counter = {//配置对象data:function(){return{num: 0,uname: "张三"}}}let app = Vue.createApp(Counter).mount('#counter') //创建应用,将配置对象传入,mount进行挂载,和上面的元素相关联
//最基础的数据绑定形式是文本插值,它使用的是“Mustache”语法(双大括号)<span>Message{{msg}}</span>
插入html使用
v-html指令
永远不要让用户输入HTML内容!
<!-- 输出带标签未解析的html --><span>{{ htmlMsg }}</span><!-- 输出解析后的html标签 --><span v-html="msg"></span>
语法糖
:
绑定单个属性<button :class="className">button</button>绑定多个属性<button v-bin="obj">button</button>动态参数 此处 attributeName 与 button 都是变量<div :[attributeName]="button">容器</div>
export default {data(){return {className:"box",obj:{class:"box",id:"id"},attributeName: 'id',button: 'button'}}}
<a v-on:[eventName]="doSomething"> ... </a>语法糖<a @[eventName]="doSomething">
<p>{{ publishedBooksMessage }}</p>
computed:{//可以理解为,定一个依赖值,只要依赖值不在变动的情况下只计算一次//计算属性只要依赖值不变,那么不会重新计算,计算属性将基于它们的响应依赖关系缓存// 一个计算属性的 getterpublishedBooksMessage() {return this.author.books.length > 0 ? 'Yes' : 'No'}},
//监听旧值与新值watch:{ //监听数据变化msg:function(newValue,OldValue){conslog.log(OldValue) //输出旧值conslog.log(newValue) //输出新值}}//监听初始值watch:{msg:{immediate: true, //布尔值开启handler(newValue){ //固定模板语法console.log(newValue) //打印初始化的值}}}//监听对象属性,深度监听wacth:{'obj.name':{deep: true, //布尔值开启 一层一层遍历 并且都加上一个侦听器handler(newValue){console.log(newValue) //进行数据替换/数据更改}}}
<p>class 类名</p>第一种放置字符串,正常使用类名<p class="active">hello</p><p>第二种放置对象(常用)</p><p :class="{active: true}">hello</p><p>第三种和字符串同时存在,不冲突</p><p :class="{active: true}" class="hello">hello</p><p>使用computed</p><p :class="classObjCom">hello</p><p>数组语法(不常用)</p><p :class="[activeClass,errorClass]">数组语法(不常用)</p><p>数组和对象结合</p><p :class="[errorClass,{active: true}]">数组和对象结合</p>
export default {data(){return {activeClass: 'active',errorClass: 'text-danger',msg:'修饰符',htmlMsg: '<h1>标题</h1>',className:"box",obj:{id: 'id',class: 'box'},isActive: true,error: null,attributeName: 'id',button: 'button',author: {name: 'John Doe',books: ['Vue 2 - Advanced Guide','Vue 3 - Basic Guide','Vue 4 - The Mystery']}}},computed:{//计算属性只要依赖值不变,那么不会重新计算,计算属性将基于它们的响应依赖关系缓存// 一个计算属性的 getterpublishedBooksMessage() {return this.author.books.length > 0 ? 'Yes' : 'No'},classObjCom(){return{active: this.isActive && !this.error,'text-danger': this.error && this.error.type === 'fatal'}}}}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号