欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

TricksinVue

程序员文章站 2022-12-05 13:05:45
there are some tricks which can't be found easily in vue.js homepage. so, for convenie...

there are some tricks which can't be found easily in vue.js homepage. so, for convenient, i summarized them here.

vue

access global variable in template

have you ever done something like this in lots of components

or

actually, you don't have to, you can register window or bus in vue.prototype like:

vue.prototype.window = window
vue.prototype.bus = bus

in the main.js or the entry file. then you can use bus or window in template directly. also, this usage prevents vue watching the attributes of bus or window which would bring a waste of performance.

reactive or not reactive

always, if we want a data reactive, we have to do something like this:

data: {
  newtodotext: '',
  visitcount: 0,
  hidecompletedtodos: false,
  todos: [],
  error: null
}

set some initial value to adds all the properties found in its data object to vue's reactivity system.

things we need to take care about is:

if we want to add reactive attributes dynamically, we have to use something like vue.set or this.$set. otherwise, they might not be reactive. if we definitely don't want some data to participate in vue's reactivity system even we initialize it in data. we can use something like object.freeze(). for example, freeze a huge array to improve performance.

scoped style won't work on dynamically inserted elements

i always use the

  

<script> export default { name: 'app', mounted() { this.$refs.app.innerhtml = `app__title` } } </script> .app__title { color: red; }

color: red won't work on .app__title because of scoped. the actual style is rendered with a unique attribute like:so, how do we solve this /deep/ or >>>.

/deep/ .app__title {
  color: red;
}

they can be used to override child component style. here is the doc.

smarter watchers

have you ever written code like this:

{
  // ...
  created() {
    this.fetchpostlist()
  },
  watch: {
    searchinputvalue() {
      this.fetchpostlist()
    }
  }
  // ...
}

actually, you can simplify it by

{
  // ...
  watch: {
    searchinputvalue:{
      handler: 'fetchpostlist',
      immediate: true
    }
  }
  // ...
}

as the doc said:

passing in immediate: true in the option will trigger the callback immediately with the current value of the expression.

$attrs and $listeners

i don't know if you have used $attrs and $listeners from this. however, i never used those until i met this situation. for example:


<script> let baseinput = { name: 'base-input', template: `

`, props: { value: { type: string } }, computed: { listeners() { const listeners = { ...this.$listeners, focus: this.focuscb } return listeners } }, methods: { focuscb(event) { console.log('child', event) } } } window.app = new vue({ el: '#app', components: { baseinput }, data: { value: '', parentplaceholder: 'parentplaceholder' }, methods: { inputcb(event) { console.log(event) }, clickcb(event) { console.log(event) } } }) </script>

it's obviously tedious to bind every attribute and listener by hand. actually, this is where $attrs and $listeners will help us. we can write the baseinput template like:

let baseinput = {
  name: 'base-input',
  template: `

`, props: { value: { type: string } }, computed: { listeners() { const listeners = { ...this.$listeners, // move `focus` in to `listeners` instead of adding one more `focus` listener. focus: this.focuscb } return listeners } }, methods: { focuscb(event) { console.log('child', event) } } }

vue-router

$router and $route

have you ever wonder about the relationship between $router and $route i give you a hint:

this.$router.currentroute === this.$route //true

vuex

commit data by one mutation

we can't directly mutate state in vuex. instead, we have to commit a mutation to mutate the data. however, it would be tedious to write lots of similar mutations like this:

let store = new vuex.store({
  modules: {
    // ...
  },
  mutations: {
    updatename(state, data) {
      state.name = data
    },
    updatechildrencount(state, data) {
      state.children.count = data
    }
    // other similar mutations
  }
})

we can write a public mutation to do this like:

let store = new vuex.store({
  modules: {
    // ...
  },
  mutations: {
    replaceproperty(state, { path, data }) {
      if (typeof path !== 'string') {
        return
      }
      path = path.split('.')
      let targetobj = path.slice(0, -1).reduce((re, key) => re[key], state)
      targetobj[path.pop()] = data
    }
  }
})

then we can mutate state in anywhere with only one mutation like:

commit(
  'replaceproperty',
  {
    path: 'name',
    data: name
  },
  { root: true }
)
commit(
  'replaceproperty',
  {
    path: 'children.count',
    data: data
  },
  { root: true }
)
commit(
  'replaceproperty',
  {
    path: 'some.other.deep.path.in.state',
    data: data
  },
  { root: true }
)

it would also work for modules!

original post

reference

7 secret patterns vue consultants don’t want you to know - chris fritz vue-loader/issues/749