跳至主要內容

VUE笔记

知识库编程技巧VUE应用VUE大约 1 分钟

计算属性(computed)

监视属性(侦听器watch)

绑定样式

  • class样式

写法:class="xxx" xxx可以是字符串、对象、数组。

  • style样式

:style="{fontSize: xxx}"其中xxx是动态值。

:style="[a,b]"其中a、b是样式对象。

条件渲染

使用v-if的时,元素可能无法获取到,而使用v-show一定可以获取到。

  • v-if 可以和 :v-else-if、:v-else一起使用。
  • v-show

收集表单数据 v-mode

过滤器(filter)

<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8" />
 <title>过滤器</title>
 <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.js"></script>
 <script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.10.6/dayjs.min.js"></script>
</head>
<body>
 <!-- 准备好一个容器-->
 <div id="root">
  <h2>显示格式化后的时间</h2>
  <!-- 计算属性实现 -->
  <h3>计算属性实现:{{fmtTime}}</h3>
  <!-- methods实现 -->
  <h3>methods实现:{{getFmtTime()}}</h3>
  <!-- 过滤器实现 -->
  <h3>过滤器实现:{{time | timeFormater}}</h3>
  <!-- 过滤器实现(传参) -->
  <h3>过滤器实现(传参):{{time | timeFormater('YYYY_MM_DD') | mySlice}}</h3>
  <h3 :x="msg | mySlice">{{msg}}</h3>
 </div>

 <div id="root2">
  <h2>{{msg | mySlice}}</h2>
 </div>
</body>
<script type="text/javascript">
 Vue.config.productionTip = false
 //全局过滤器,必须在new Vue({})之前
 Vue.filter('mySlice', function (value) {
  return value.slice(0, 4)
 })
 new Vue({
  el: '#root',
  data: {
   time: 1621561377603, //时间戳
   msg: '你好,程序员'
  },
  computed: {
   fmtTime() {
    return dayjs(this.time).format('YYYY年MM月DD日 HH:mm:ss')
   }
  },
  methods: {
   getFmtTime() {
    return dayjs(this.time).format('YYYY年MM月DD日 HH:mm:ss')
   }
  },
  // 局部过滤器
  filters: {
   timeFormater(value, str = 'YYYY年MM月DD日 HH:mm:ss') {
    return dayjs(value).format(str)
   }
  }
 })
 new Vue({
  el: '#root2',
  data: {
   msg: 'hello,dev!'
  }
 })
</script>
</html>