Vue学习二、基本语法
一、绑定数据,绑定属性,绑定html,循环数据
<template> <div> <p>绑定数据:{{msg}}p> <p>绑定对象:{{userInfo.userName}}p> <p v-html="htmlSrc">p> <img v-bind:src="logSrc" alt="logo图片1" /> <img :src="logSrc" alt="logo图片2" /> <p :title="titleStr">把鼠标放上去看看p> <a :[myHref]="hrefStr">{{hrefStr}}a> <a :[myHref]="'https://www.baidu.com/'">{{hrefStr}}a> <ul> <li v-for="(item, index) in list" :key="index"> {{item}}---{{index}} li> ul> <ul> <li v-for="(item, index) in listObj" :key="index" > {{item.title}} li> ul> <p>循坏二维数组p> <ul> <li v-for="(item, index) in listArr" :key="index"> {{item.title}} <ol> <li v-for="(title, i) in item.list" :key="i"> {{title}} li> ol> li> ul> div> template> <script> export default { name: 'App', data() { return { msg: "绑定数据", userInfo: { userName: "张三", userAge: 20 }, htmlSrc: "我是标签", logSrc: "/img/logo.82b9c7a5.png", titleStr: "我是title", myHref: "href", hrefStr: "https://www.baidu.com/", list: ["html","javaScript","CSS"], listObj: [ {title: "html"},{title: "javaScript"} ], listArr: [ {title: "html", list:["h1","p","div"]},{title: "javaScript",list:["event","function","window"]} ] } } } script>
二、定义方法
在methods 对象中定义方法,元素通过@click绑定点击方法
<template> <div> <input value="点击" type="button" @click="clickFun"/> div> template> <script> export default { name: 'App', data() { return { } }, methods: { clickFun() { console.log("23"); } } } script>
三、通过bind绑定class属性值
<template> <div> <input value="点击" type="button" @click="clickFun"/> <div :class="className">div> div> template> <script> export default { name: 'App', data() { return { className: "red" } }, methods: { clickFun() { this.className = "blue"; } } } script>
通过v-bind修改属性值:class绑定多个值
<template> <div> <input value="点击" type="button" @click="clickFun"/> <div :class="{'red': isRed, 'blue': isBlue}" >div> <div :class="[isRed? redClass : blueClass]">div> div> template> <script> export default { name: 'App', data() { return { isRed: false, isBlue: false, redClass: "red", blueClass: "blue" } }, methods: { clickFun() { this.isRed = true; this.isBlue = true; } } } script>
循环渲染数据 把第1条和第二条分别为红色,蓝色
<template> <div> <ul> <li v-for="(item, index) in list" :key="index" :class="{'red': index == 0, 'blue':index==1}"> {{item}} li> ul> div> template> <script> export default { name: 'App', data() { return { list:["html", "css", "vue", "script"] } }, methods: { clickFun() { this.isRed = true; this.isBlue = true; } } } script>
四、绑定多个style
<template> <div> <div :style="[blueStyle, redStyle]">绑定多个stylediv> div> template> <script> export default { name: 'App', data() { return { blueStyle: { fontSize: "20px", color: "blue" }, redStyle:{ background: "red" } } }, methods: { clickFun() { this.isRed = true; this.isBlue = true; } } } script>