2

As the title, I want to add watcher and the same callback for all of the props, but I neet to code like this in sub-component:

<script>
export default {
  props: {
    a: String,
    b: String,
    c: String
  },
  watch: {
    a (v) { this.handler(v) },
    b (v) { this.handler(v) },
    c (v) { this.handler(v) },
  },
  methods: {
    handler (v) {
      // code...
    }
  }
}
</script>

And do you know how to simplify this?

1 Answer 1

2

Use a function to build your component.

function buildComponent(properties){
  const base = { methods:{ handler(v){ console.log(v) }}, props:{}, watch:{}}

  for (let prop of properties){
    base.props[prop] = String
    base.watch[prop] = function(v) {this.handler(v)}
  }
  return base
}

export default buildComponent(["a","b","c"])

Vue is just javascript.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.