Web development and Tech news Blog site. WEBISFREE.com

HOME > vuejs

Issue with forceUpdate() Not Working in Vue2 Plugin Composition API

Last Modified : 11 Oct, 2023 / Created : 12 Oct, 2023
181
View Count
There are many cases where the core feature of Vue, the composition-api, is used in Vue2 without using Vue3. Various reasons (such as the availability of plugin support and stability) account for this. Here, we will look at the method for cases where this.forceUpdate() does not work.


Reason this.forceUpdate() Doesn’t Work
Firstly, the problem occurs because the composition api does not fully functionally implement Vue3's reactivity. Therefore, if a rendering-related issue occurs for this reason, executing this.$forceUpdate() may not resolve the issue.


Solving Rendering Issues Using $set in the Composition API


The simplest solution is to use $set() when updating data that needs rendering. Thus, $set is the easiest and simplest method available to fix the reactivity issue of an object for rendering.

// $set: Tracks objects with reactivity and updates the view, performing rendering.

Here's a simple syntax.

$set(target object, object key, object value)

Simply by using $set on objA like below without using $forceUpdate(), the issue of not rendering can be resolved. $set can be accessed from the context's root.


Example of Using $set
Below is a simple example code. It’s a method used in the Composition API using $set().
setup(emit, { root }) {
  ...
  const updateData = () => {
    root.$set(objA, 'name', 'abc')
  }
}

Using the above example, the value of the name of the objA object will be updated to 'abc' and immediately appear rendered. It was a simple rendering issue resolution method.

You can also add new properties to an object using $set.


Adding New Property to Object Using $set


The example below is a simple one that adds a new property, newMessage, to objB which is held in Vue's data.
export default {
  data() {
    return {
      objA: {
        message: 'Hello Vue!'
      }
    };
  },
  methods: {
    addProperty() {
      this.$set(this.objA, 'newMessage', 'Hello OpenAI!');
    }
  }
};

Looking at the above example, there is an addProperty() method. When this method is executed, a new key and value will be added to objB.


Up to this point, we've looked at the rendering issue resolution method and a simple example of using $set.

Perhaps you're looking for the following text as well?

    Previous

    How to add templates to components using VueJS's v-slot and check for slot existence