简体   繁体   中英

Is there a proper way to mutate a Vue prop from an external Javascript?

I'm working on a site made using PHP templates and jQuery, with a table rendered using Vue:

let vuetablecomponent= new Vue({
  components: { ManualTable },
}).$mount('[data-vue-app=manualtable]');

I need to be able to manipulate the state of the Vue table from the outside. Currently I'm manipulating the props directly using JS, like this:

vuetablecomponent.$children[0].aprop = 'propvalue'

And of course, I got a warning from Vue:

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value.

Technically this shouldn't be a problem, since the parent component is not a Vue component, and I do want the value to be overwritten if the page is re-rendered by PHP. But I'm wondering if there's a more... proper way to do this.

How do you render the component and pass the prop to the component on first render?

Whether you use PHP templates or plain HTML, you still have to initialize the Vue app somehow because otherwise how would the browser know how to load a Vue component?

You either did:

Method A (use render method):

--- init-app.js --
new Vue({
  el: '#app',
  render: h => h(App)
})


-- App.vue --
<template>
  <MyTableComponent :a-prop="tableProp" />
</template>

<script>
export default {
  data() {
    return {
      tableProp: "123-abc",
    };
  },
}
</script>

If above is the case, just create a reference to this component like so:

mounted() {
  window.__APP__ = this
}

then update the tableProp wherever you want by doing window.__APP__.tableProp = "new-value"

Method B (use html content as template):

--- index.php ---
<?php
<html>
  <body>
    <div id="app">
      <MyTableComponent :a-prop="tableProp"></MyTableComponent>
    </div>
  </body>
</html>
?>
new Vue({
  el: "#app",
  component: {
    MyTableComponent,
  },
  data: {
    tableProp: "123-abc",
  }
})

If this is the case, just create a reference to the app like so:

window.__APP__ = new Vue({})

make sure Vue gets loaded first before your script that updates this prop so the variable is actually set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM