Vue核心知识-Vue的数据绑定

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/grapelove01/article/details/82462805

模板绑定

{{}} 中可以进行简单的一元、二元运算,但不能写语句

import Vue from 'vue'

new Vue({
  el: '#root',
  template: `
    <div>V
      {{isActive ? 'active' V: 'not active'}}
      {{arr.join(' ')}}
    </div>
  `,
  data: {
    isActive: false,
    arr: [1, 2, 3]
  }
})

调用全局变量

template: `
    <div>
      {{Date.now()}}
    </div>
  `,

vue 中,在模板里可以访问的,一个是绑定到 this 上的所有值,是可以访问到的;一个是 vue 自建的白名单,默认的 JS 的全局对象,也是可以访问到的。

但是自己定义在外层的全局变量是不能访问的。

// 控制台报错
var globalVar = '111' // eslint-disable-line
new Vue({
  el: '#root',
  template: `
    <div>
      {{globalVar}}
    </div>
  `  
})

绑定 html

使用 v-html 指令

new Vue({
  el: '#root',
  template: `
    <div>
      <p v-html="html"></p>
    </div>
  `,
  data: {
    html: '<span>123</span>'
  }
})

动态绑定属性

v-bind 指令,简写 :

new Vue({
  el: '#root',
  template: `
    <div :id="aaa">
    </div>
  `,
  data: {
    aaa: 'main'
  }
})

绑定事件

v-on 指令,简写 @

import Vue from 'vue'

new Vue({
  el: '#root',
  template: `
    <div :id="aaa" @click="handleClick">
      <p v-html="html"></p>
    </div>
  `,
  data: {
    aaa: 'main',
    html: '<span>123</span>'
  },
  methods: {
    handleClick () {
      alert('clicked') // eslint-disable-line
    }
  }
})

vue 对这种绑定方式做过优化,不用担心性能上的问题,和事件委托对比。

动态绑定 Class

import Vue from 'vue'

new Vue({
  el: '#root',
  template: `
    <div :id="aaa" :class="{active: !isActive}">
      <p v-html="html"></p>
    </div>
  `,
  data: {
    isActive: false,
    aaa: 'main',
    html: '<span>123</span>'
  }
})

数组的写法

<div :id="aaa" :class="[isActive ? 'active' : '']">

数组和对象合并的写方法

<div :id="aaa" :class="[{active: isActive}]">

这种写法,方便我们合并多个动态 Class

通过 computed

通过 computed 返回一个完整的对象,再绑定 class

动态绑定 Style

import Vue from 'vue'

new Vue({
  el: '#root',
  template: `
    <div
      :style="styles"
    >
      <p v-html="html"></p>
    </div>
  `,
  data: {
    html: '<span>123</span>',
    styles: {
      color: 'red'
    }
  },
})

数组、对象合并的写法

new Vue({
  template: `
    <div
      :class="[styles, styles2] "
    >
      <p v-html="html"></p>
    </div>
  `,
  data: {
    html: '<span>123</span>',
    styles: {
      color: 'red'
    },
    styles2: {
      color: 'black'
    }
  }
})

vue 会自动添加 prefix

vue 会根据浏览器对样式进行判断,需要加前缀的都会加上去。

styles: {
      color: 'red',
      appearance: 'none'
    },

chorme看得到的结果

<div id="main" class="color appearance color" style="color: red; -webkit-appearance: none;"><p><span>123</span></p></div>

猜你喜欢

转载自blog.csdn.net/grapelove01/article/details/82462805
今日推荐