1. 首页
  2. 软件开发
  3. Vue3的条件渲染,列表渲染、双向绑定、计算属性,数据监听器等的语法

Vue3的条件渲染,列表渲染、双向绑定、计算属性,数据监听器等的语法

  • 发布于 2024-08-17
  • 16 次阅读

本文主要记录Vue 3 中的条件渲染、列表渲染、双向绑定、计算属性、数据监听器等语法和使用方式。

1. 条件渲染

条件渲染可以通过 v-if 和 v-else 指令来实现。

<template>
  <div>
    <p v-if="isDisplayed">This paragraph is displayed</p>
    <p v-else>This paragraph is hidden</p>
    <button @click="toggleDisplay">Toggle Display</button>
  </div>
</template>

<script>
import {
    ref } from 'vue';

export default {
   
  setup() {
   
    const isDisplayed = ref(true);

    function toggleDisplay() {
   
      isDisplayed.value = !isDisplayed.value;
    }

    return {
   
      isDisplayed,
      toggleDisplay
    };
  }
};
</script>

2. 列表渲染

列表渲染可以通过 v-for 指令来实现。

<template>
  <ul>
    <li v-for="item in items" :key="item.id">{
   {
    item.name }}</li>
  </ul>
</template>

<script>
import {
    ref } from 'vue';

export default {
   
  setup() {
   
    const items = ref([
      {
    id: 1, name: 'Item 1' },
      {
    id: 2, name: 'Item 2' },
      {
    id: 3, name: 'Item 3' }
    ]);

    return {
   
      items
    };
  }
};
</script>

3. 双向绑定

双向绑定可以通过 v-model 指令来实现。

<template>
 <input type="text" v-model="message" />
 <p>{
   {
    message }}</p>
</template>

<script>
import {
    ref } from 'vue';

export default {
   
 setup() {
   
   const message = ref('');

   return {
   
     message
   };
 }
};
</script>

4. 计算属性

计算属性可以通过 computed 函数来定义。

<template>
  <div>
    <p>{
   {
    fullName }}</p>
  </div>
</template>

<script>
import {
    ref, computed } from 'vue';

export default {
   
  setup() {
   
    const firstName = ref('John');
    const lastName = ref('Doe');

    const fullName = computed(() => {
   
      return `${
     firstName.value} ${
     lastName.value}`;
    });

    return {
   
      fullName
    };
  }
};
</script>

5. 数据监听器

在Vue 3中,数据监听器可以通过 watch 函数来实现

<template>
<div>
  <p>{
   {
    count }}</p>
  <button @click="increment">Increment Count</button>
</div>
</template>

<script>
import {
    ref, watch } from 'vue';

export default {
   
setup() {
   
  const count = ref(0);

  function increment() {
   
    count.value++;
  }

  watch(count, (newVal, oldVal) => {
   
    console.log(`Count changed from ${
     oldVal} to ${
     newVal}`);
    // 在这里可以执行其他操作,比如发送请求或更新其他数据
  });

  return {
   
    count,
    increment
  };
}
};
</script>

上面代码中使用 watch 函数来监听 count 数据的变化。当 count 发生变化时,会触发回调函数并执行相应的操作。在回调函数中,可以访问新值 newVal 和旧值 oldVal ,并在需要时执行其他操作。

原文链接: https://blog.csdn.net/2401_82884096/article/details/136968349