likes
comments
collection
share

vue3基础语法(二)

作者站长头像
站长
· 阅读数 32

一.计算属性

在vue3中计算属性在computed中定义,下面是具体例子

<template>
    <p>结果是{{result}}</p>
</template>

<script>
export default {
  name: "computed",
  data(){
    return {
      number1:10,
      number2:20
    }
  },
  computed:{
    result(){ 
      return this.number1+this.number2
    }
  }
}
</script>

<style scoped>

</style>

他其实类似于你定义好一个计算方法然后调用的时候会运行,但是既然两者如此相似,那么计算属性存在的意义又是什么呢。 其实,计算属性会缓存响应数据,大概意思就是,你的number1或者number2没有发生改变的话,他就不会重新计算,而如果是方法的话,那么每次调用都会重新计算,也就是性能方面的影响

二.class属性绑定 我们经常可以针对class属性是否显示,增加判断值,或者多属性绑定,我们来看看

<template>
  <p :class="{'active':isactive,'text-danger':haserror}">class的样式绑定</p>
  <p :class="classObject">class的样式绑定2</p>
  <p :class="[arractive,arrhaserror]">class的样式绑定3</p>
</template>

<script>
export default {
  name: "Classdemo",
  data() {
    return {
      isactive: true,
      haserror: true,
      arractive:'active',
      arrhaserror:'text-danger'
    }
  },
  computed: {
    classObject() {
      return {
        'active': this.isactive,
        'text-danger': this.haserror,
      };
    },
  },


}
</script>

<style scoped>
.active {
  font-size: 45px;
}

.text-danger {
  color: red;
}
</style>

这里的例子有三种样式绑定方法,我也分别用了基础方法,计算属性方法,列表进行绑定,前后两个知识点也联系起来。 三.style绑定对象


<template>
<p :style='{color:activecolor,fontSize:"30px"}'>style绑定1</p>
<p :style='styleobject'>style绑定2</p>
</template>

<script>
export default {
  name: "styledemo",
  data(){
    return {
      activecolor:"green",
      styleobject:{
        color:'red',
        fontSize:"30px"
      }
    }
  }
}
</script>

<style scoped>

</style>

类似于class绑定,不多说了

四.侦听器(watch) 侦听器的可以用来侦测响应式数据的变化

<template>
  <p>{{ message }}</p>
  <button @click="updatamsg">修改数据</button>
</template>

<script>
export default {
  name: "watchdemo",
  data() {
    return {
      message: '我在学vue'
    }
  },
  methods: {
    updatamsg() {
      this.message = '我在学vue3,不学vue2了'
    }
  },
  // 这里的函数名必须要和侦听的数据名称一致,
  //newvalue代表新的数据
  //oldvalue代表旧的数据
  watch:{
    message(newvalue,oldvalue){
      console.log(newvalue,oldvalue)
    }
  }

}
</script>

<style scoped>

</style>

当然这里的newvalue,oldvalue可以用任意参数表示

五.模板引用

这个名字比较抽象,你可以理解为是对Dom元素的操作

<template>
  <div>
    <p ref="container" class="container">{{ content }}</p>
    <button @click="editdom">点点看</button>
    <div></div>
    <input type="text" ref="username">
    <p>{{ usernameValue }}</p>
  </div>
</template>

<script>
export default {
  name: "domdemo",
  data() {
    return {
      content: "内容",
      usernameValue: "",
    };
  },
  methods: {
    editdom() {
      this.$refs.container.innerText = '我爱学vue3';
      this.usernameValue = this.$refs.username.value;
    },
  },
};
</script>

<style scoped>
/* 样式 */
</style>

主要是通过ref来连接双方,你可以对dom进行操作,但是说实话,这个功能用的应该不多,而且性能消耗较高,一般没有必要用这个功能,这里放这里作为参考