Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue this.$set方法

作者:末世修罗   发布日期:2025-12-03   浏览:47

// 示例代码:使用 Vue 的 this.$set 方法

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!',
    obj: {
      name: 'Vue'
    }
  },
  methods: {
    updateMessage() {
      // 直接修改 message,Vue 可以检测到变化并更新视图
      this.message = 'Hello World!';
    },
    addObjectProperty() {
      // 使用 this.$set 添加新属性,确保 Vue 检测到变化并更新视图
      this.$set(this.obj, 'age', 3);
    }
  }
});

// HTML 部分
<div id="app">
  <p>{{ message }}</p>
  <p>{{ obj.name }} - {{ obj.age }}</p>
  <button @click="updateMessage">Update Message</button>
  <button @click="addObjectProperty">Add Object Property</button>
</div>

// 解释说明:
// 1. `this.$set` 是 Vue 提供的一个方法,用于向响应式对象中添加新的属性,并确保这个属性也是响应式的。
// 2. 如果直接在已有的响应式对象上添加新属性(例如 this.obj.newProp = value),Vue 无法检测到这个变化,因此不会更新视图。
// 3. 使用 `this.$set(target, propertyName/index, value)` 可以确保新添加的属性是响应式的,参数分别是目标对象、属性名或数组索引、新值。

上一篇:vue 获取当前路由

下一篇:vue文件

大家都在看

vue.js devtools用法

vue js for循环

highlight.js vue

vue.config.js 配置

vue.config.js 配置代理

vue.config.js configu

node.js vue

vue3组件传值的方式

vue3 子路由

vue3 router传参

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站