Vue.js v2 Resources

The initial goal was to override a WordPress plugin’s image slider pagination thumbnails for desktop and mobile. I didn’t even know the plugin was using Vue.js. A lot of learning along the way about Vue instances, components, data, methods, and prototype. Still haven’t yet reached the goal of overriding the plugin’s Vue.js v2 settings, but this list of resources is getting me there.

Note: While the current version is Vue.js v3 (v3.2.45 as of Nov 11, 2022), the WordPress image slider I’m trying to edit is Vue.js v2, so everything listed below focuses on Vue.js v2.

Vue Js Methods – Demystified – DigitalYA

Vue methods are objects associated with a Vue instance. Vue js methods are functions that trigger certain actions as commanded by the user. They are commonly used for event handling. A method named by the key of the object returns an object.

Some of the most common use cases for a method in VueJS are actions performed when clicking a button or in order to enter data in a text input.

Personal note: I don’t think Vue JS methods will help me update what I want to update in a 3rd-party plugin: spaceBetween: 10 in Vue.prototype.sliderThumbs function. Maybe computed is a better route.

Computed Props and Watchers — What’s the Difference? – Michael N Thiessen

The main use case for computed props, as discussed before, is in composing data from other data.

Another one is allowing us easier access to nested data.

If we had some deeply nested data in our component that we needed access to, like data.nested.really.deeply.importantValue, we can simplify this a whole lot:

computed() {
  importantValue() {
    return this.data.nested.really.deeply.importantValue;
  },
}

And now we only need to write this.importantValue to get ahold of it!


Components Basics – Vuejs.org


List Rendering – Vuejs.org (last section on page: Vue.component(‘todo-item’, {):

methods: {
    addNewTodo: function () {
      this.todos.push({
        id: this.nextTodoId++,
        title: this.newTodoText
      })
      this.newTodoText = ''
    }
  }

Plugins – Vuejs.org (section #4: Add some Vue instance methods by attaching them to Vue.prototype.):

// 4. add an instance method
  Vue.prototype.$myMethod = function (methodOptions) {
    // some logic ...
  }

Reactivity in Depth – Vuejs.org (last section on page: last “Since $nextTick() returns a promise…”):

methods: {
  updateMessage: async function () {
    this.message = 'updated'
    console.log(this.$el.textContent) // => 'not updated'
    await this.$nextTick()
    console.log(this.$el.textContent) // => 'updated'
  }
}

Vue.js v2 Video Tutorial – The Net Ninja

Vue JS 2 Tutorial #1 – Introduction – The Net Ninja

Prototype (eg: Vue.prototype.$blogName = ‘String of Text’)

What prototype is used for – Vue version 2 Cookbook

Adding Instance Properties

There may be data/utilities you’d like to use in many components, but you don’t want to pollute the global scope. In these cases, you can make them available to each Vue instance by defining them on the prototype:

Vue.prototype.$appName = 'My App'

Now $appName is available on all Vue instances, even before creation. If we run:

new Vue({
  beforeCreate: function() {
    console.log(this.$appName)
  }
})

Then "My App" will be logged to the console!

The Context of Prototype Methods

Methods added to a prototype in JavaScript gain the context of the instance. That means they can use this to access data, computed properties, methods, or anything else defined on the instance.

When Not Using a Module System

Now the source of these shared properties is more obvious: there’s an App object defined somewhere in the app. To find it, developers can run a project-wide search.

Another advantage is that App can now be used anywhere in your code, whether it’s Vue-related or not. That includes attaching values directly to instance options, rather than having to enter a function to access properties on this.

How does JavaScript .prototype work? – Stack Overflow

In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it.

Change Vue prototype variable in all components – Stack Overflow

Original poster: I’m wanting to change the global variable below throughout the page:

Vue.prototype.$color = 'green';

See possible answers.

Accessing properties globally in Vue.js with prototypes – LogRocket

Instead of accessing a global property (components and resources) through repeated import statements, it’s more efficient to use prototype, which allows access to a global property through a property statement.

Prototype is a more efficient way to access a global property (components and resources), that uses a property statement instead of using less efficient multiple import statements.

Sample: Vue.prototype.$blogName = ‘LogRocket’

  • blogName is the property or data name.
  • LogRocket string is the value. With this definition, Vue.js gets this property (the blog name, in this case) available to every Vue instance in the entire project even before the instance is created.
  • The $ sign is used in Vue.js to identify properties that can be used in all available instances in any given Vue project.

A lot of data values, properties, and utilities like HTTP resources can be made global properties with Vue prototypes.

Example (from WordPress Smart Variation Images plugin code) showing how prototype uses this to access data, computed properties, and even other methods inside any Vue instance in the project.

  • Property name: sliderThumbs
  • Keyword: this
mounted: function() {
                    this.disable_thumb || (this.galleryThumbs = this.sliderThumbs()), this.galleryTop = this.sliderMain(), this.thumbImages_static(), this.mainImage_slider_thumbadd()
                },
Vue.prototype.sliderThumbs = function() {
                var t = this,

Modifying Vue Instances – How To Create Custom Vue.js Plugins – Digital Ocean

To add a property or method directly to component instances without any injection mechanism, you can modify the Vue prototype.


Lifecycle Hooks; Path connecting mounted > this > prototype

Easy Way to Understand the VueJS Component Lifecycle Hooks – Edutechional

Easy Way to Understand the VueJS Component Lifecycle Hooks – Edutechional

Registering Lifecycle Hooks – Vue v2

All lifecycle hooks are called with their this context pointing to the current active instance invoking it.

  • mounted: function() – mounted is a Lifecycle Hook
  • this.sliderThumbs() – this is pointing directly to sliderThumbs. sliderThumbs is the current active instance invoking this on mounted
  • Vue.prototype.sliderThumbs – sliderThumbs is the current active instance being pointed to by this in this.sliderThumbs()

Example:

const a = {
                components: {},
                name: "SliderComponent",
                mounted: function() {
                    this.sliderThumbs()
}
},
Vue.prototype.sliderThumbs = function() {
                var t = this,
                    i = {
                        spaceBetween: 10
}

Extend method in Vue v2

  • How to globally override properties of a 3rd party component in VueJS – Stack overflow
    • Original poster’s question: Given that we have no control on the component, how can we set those property defaults globally?
  • Overriding a component method – Stack Overflow
    • Original poster: All I need is to override this method to convert the options before passing them to the ChartWrapper. But how? I haven’t found a way to simply override a component method in Vue docs. I could create a new component and pass the converted options down, but I need access to the Google object, which is only loaded internally by the plugin.
import VueChart from "vue-charts";
Vue.use(VueChart);
const BaseChart = Vue.options.components["vue-chart"];
const CustomChart = BaseChart.extend({
  methods:{
    buildWrapper (chartType, dataTable, options, containerId) {
      let wrapper = new google.visualization.ChartWrapper({
        chartType: chartType,
        dataTable: dataTable,
        options: google.charts.Bar.convertOptions(options),
        containerId: containerId
      })
      return wrapper
    }
  }
});
Vue.component("custom-chart", CustomChart);

Update Entire Observed Array and Trigger Re-render

Vue.js v2 best way to update entire array – Stack Overflow

oldArr = newArr

Read more at: Vue.js v2 Replacing an Array

Another option might be to to empty the array and then push() the new one like:

yourArray.push(... yourNewArray) //pushes all new items

Code source: Stack Overflow comment

Also see Array Change Detection in Vue JS v2 documentation. Sections:

More about Vue watch() outputs same oldValue and newValue – Stack Overflow


Vue watch() outputs same oldValue and newValue – Stack Overflow

  • new Vue, mounted, watch, computed, newVal, oldVal

How to push items into an array in the data object in Vue.js? – The Web Dev

To push items into an array in the data object in Vue.js, we can make a copy of the object to append to the array before we call push with it.

See article for code example.

Call this.queue.push with the copy of the this.purchase object.

Making a copy of the object will mean that only the original this.purchase object when we change the properties in it rather than this.purchase and the item in the this.queue array.


Mixins – Vue.org v2

Personal note: Seems a mixin (either as a separate mixin.js file or part of the main.js file) needs to be injected inside the component of the 3rd-party plugin I’m trying to update, where the functionality should come into play. Unfortunately, I won’t be able to add any code inside the 3rd-party plugin, so maybe mixin isn’t going to allow me to alter options in the plugin’s Vue.prototype.sliderThumbs function.

A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.

Option Merging:

When a mixin and the component itself contain overlapping options, they will be “merged” using appropriate strategies.

Options that expect object values, for example methodscomponents and directives, will be merged into the same object. Note that the same merge strategies are used in Vue.extend().

Global Mixin:

Use with caution! A global mixin will affect every Vue instance created afterwards. When used properly, this can be used to inject processing logic for custom options.

Custom Option Merge Strategies:

When custom options are merged, they use the default strategy which overwrites the existing value. If you want a custom option to be merged using custom logic, you need to attach a function to Vue.config.optionMergeStrategies:

Vue.config.optionMergeStrategies.myOption = function (toVal, fromVal) {
  // return mergedVal
}

How to Manage Vue Mixins – LearnVue

Mixin objects can use any of the component options — data, mounted, created, update, etc — and when a component uses a mixin, all of the information in the mixin object will be, well, mixed in to the component.

Then, the component has access to all of the options in the mixin as if you declared it in the component itself.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *