【问题标题】:How would I add data on a button press to the either the root or a component of Vue 3?如何将按下按钮时的数据添加到 Vue 3 的根目录或组件?
【发布时间】:2022-01-08 13:57:08
【问题描述】:

我的主要问题是我试图将数据被动地添加到 Vue 根或 Vue 组件。这是一个问题的原因是,一旦我的 Vue 应用程序实例被挂载(使用 app.mount()),我就无法响应性地将数据添加到 Vue 应用程序。我正在尝试将 Vue 与 vanilla JS 一起使用,因为我是该框架的新手。我想它真正归结为...有什么我可以触发的事件或我可以在 vanilla JS 中调用的对象以将新数据插入到 Vue 应用程序实例中的对象数组中?

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    最简单的方法是将Vuex 安装到您的 vue 3 应用程序中并通过 vuex 商店注入数据。

    这里是使用命令vue create my-vue-prj从 vue-cli 生成的简单的 vue3 项目

    {
      "name": "my-vue-prj",
      "version": "0.1.0",
      "private": true,
      "scripts": {
        "serve": "vue-cli-service serve",
        "build": "vue-cli-service build",
        "lint": "vue-cli-service lint"
      },
      "dependencies": {
        "core-js": "^3.6.5",
        "vue": "^3.0.0",
        "vuex": "^4.0.0-0"
      },
      "devDependencies": {
        ...((skipped))...
      }
    }
    

    还有src/main.js 入口点。

    import { createApp } from "vue";
    import App from "./App.vue";
    import store from "./store";
    
    const app = createApp(App);
    app.use(store).mount("#app");
    
    window.vueApp = app;
    // or can expose store directly
    // window.store = store; 
    
    • 公开 vue 应用实例 (window.vueApp) 以从外部 javascript 访问。

    Vuex store 可以这样访问。

    // external.js
    const store = window.vueApp.config.globalProperties.$store
    /*
     * can inject(modify, delete, etc) data into vue app through `store`
     */
    

    演示

    像这样在 vuex 存储中定义一个数组

    // file : src/store/index.js
    import { createStore } from "vuex";
    
    export default createStore({
      state: {
        nums: [0, 1, 2],
      },
      mutations: {
        replaceNum(state, nums) {
          state.nums = nums;
        },
      },
      actions: {},
      modules: {},
    });
    
    • 数组nums要在App.vue中渲染

    数组nums可以从组件App.vue访问。

    <template>
      <img alt="Vue logo" src="./assets/logo.png" />
      <ul>
        <li v-for="(n, index) in $store.state.nums" :key="index">{{ n }}</li>
      </ul>
    </template>
    
    • $store.state.nums 是 [0, 1, 2] 的数组
    • li 以文本 (0, 1, 2) 呈现

    数组 nums 可以从外部 js 更新

    // external.js
    const store = window.vueApp.config.globalProperties.$store
    store.commit('replaceNum', [2, 3, 5, 7, 11]);
    
    • commit('replaceNum', ...) - 在突变中调用方法replaceNum。它更新了nums,内容也被刷新了。

    【讨论】:

      猜你喜欢
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 2020-08-18
      • 2021-04-21
      • 1970-01-01
      • 2018-04-06
      相关资源
      最近更新 更多