vue的基本指令

基本指令

  • 项目入口文件
import Vue from 'vue'
import App from './App'

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})
  • 组件
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

支持ES6语法:

<h1>{{ `${msg}` }}</h1>
  • v-html,以HTML形式输出
<div v-html="msg"></div>
  • v-text,以纯文本形式输出
<div v-text="msg"></div>
  • v-bind: 绑定属性
<img v-bind:src="url" />

简写形式: <img :src="" />

  • v-on:click 事件绑定

条件渲染

  • v-if v-else-if v-else
<div v-if="ok">aaa</div>
<div v-else>bbb</div>
  • 在template上使用条件渲染
<template v-if="ok">aaa</template>
<template v-else>bbb</template>
  • v-show :``display:none

列表渲染

  • v-for
<ul>
    <li v-for="user in users">
        {{user.username}} | {{user.age}}
    </li>
</ul>
<ul>
    <li v-for="(item,index) in users" :key="index">
        {{item.username}}
    </li>
</ul>

事件监听

  • v-on:click
<button v-on:click="handlerAddUser">添加用户</button>
<button @click="handlerAddUser">添加用户</button>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  methods: {
    handlerAddUser() {
      alert(this.msg)
    }
  }
}
</script>
  • 参数传递
<button @click="handlerAddUser(msg, $event)">添加用户</button>

事件修饰符

  • .stop 阻止事件冒泡
  • .prevent 阻止默认时间

  • .once 一次

  • .submit 提交事件

  • .keyup.enter 回车事件
  • .keydown.enter 回车事件

变异方法

这些变异方法会引起视图的变化:

  • push({})
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

计算属性

<h1>{{ msgReverse }}</h1>
<script>
computed: {
    msgReverse(){
        return this.msg.split('').reverse().join('')
    }
}
</script>

计算属性和方法的优势:计算属性存在缓存

猜你喜欢

转载自www.cnblogs.com/zhuxiang1633/p/10548311.html