vue变量

setup(props, context):初始化变量、函数

  • ref定义变量,可以用.value属性重新赋值
  • reactive定义对象,不可重新赋值,当他的值发生改变(一般是对象中的某一个属性改变)会将有使用这个对象的组件重新渲染一遍。
  • props存储父组件传递过来的数据
  • context.emit():触发父组件绑定的函数

vue 中通过 setup() 函数来初始化变量。setup函数写在 export default {} 中,可以用 setup = () => {} 即箭头函数的写法,也可以直接写作 setup()
例子:

  1. export default {
  2. name: 'UserProfileView',
  3. components: {
  4. ContentBase,
  5. UserProfileInfo,
  6. UserProfilePosts
  7. },
  8. setup() {
  9. const user = reactive({
  10. id: 1,
  11. username: "heky",
  12. lastName: "he",
  13. firstName: "ky",
  14. followerCount: false,
  15. });
  16. return {
  17. user,
  18. }
  19. }
  20. }

这个例子中定义了一个user的变量对象,里面放着5各变量,之后将要用到的变量对象 user return出去

之后可以在子组件的标签中用 v-bind: 来绑定
例如:

  1. <UserProfileInfo v-bind:user="user"/>

v-bind: 也可以省略为 : ,例如:

  1. <UserProfileInfo :user="user"/>

等号后面的冒号可以传入一个表达式,这里将 user 传入

之后要在组件中使用,需要将用到的组件放到 export default{}propsprops 是一个对象。
例如:

  1. export default {
  2. name: "UserProfileInfo",
  3. props: {
  4. user: {
  5. type: Object,
  6. required: true,
  7. },
  8. }
  9. }

其中user也是作为一个对象来写,有两个值,一个是类型,另外一个是是否需要。
这样写完之后就可以在 template 中用了,使用时用两个大括号括起来 {{}}
例如:

  1. <div class="username">{{ user.username }}</div>
  2. <div class="fans">fans: {{ user.followerCount }}</div>

如果想作为属性的值进行使用,可以在对应的属性前面加上 :
例如:

  1. <img :src="user.photo" alt="" class="img-fluid" >

这里的 user.photo 是一个变量而不是当作一个字符串,作用于src这个属性,所以src前面加上一个冒号( :v-bind: 的简写)

如果需要对变量进行计算然后实现动态变化,需要在组件中设置一个新的变量,以及用到vue中的 computed 函数
例如:

  1. import { computed } from 'vue';
  2. export default {
  3. name: "UserProfileInfo",
  4. props: {
  5. user: {
  6. type: Object,
  7. required: true,
  8. },
  9. },
  10. setup(props) {
  11. let fullname = computed(() => props.user.firstName + ' ' + props.user.lastName);
  12. return {
  13. fullname
  14. }
  15. }
  16. }

这里setup函数传入一个变量props表示当前组件的props,然后在里面定义了一个新的变量 fullname 调用 computed 函数动态计算变量的值,注意 computed 函数接收一个函数,之后也是一样将要用到的变量return出去就可以了。
在template中使用:

  1. <div class="username">{{ fullname }}</div>

使用 v-model 属性获取html标签内的内容示例:

  1. <template>
  2. <textarea v-model="content" class="form-control" id="edit-post" rows="3"></textarea>
  3. </template>
  4. <script>
  5. import { ref } from 'vue';
  6. export default {
  7. name: "UserProfileWrite",
  8. setup() {
  9. let content = ref("");
  10. return {
  11. content,
  12. }
  13. }
  14. }
  15. </script>

变量对象可以用 reactive ,单个变量可以使用 ref 。示例中使用 v-model 将textarea中的内容绑定到content这个变量中,之后要取得这个值可以用 content.value 来取。之后如果要修改这个值也可以直接对 content.value 进行赋值。

注:其实用 reactive 也是可以赋值的,不过是对对象中的属性赋值,一般如果变量是对象就用 reactive 否则可能就用 ref

添加新评论