繁体   English   中英

Vue/nuxt - 如何从子组件访问父级引用

[英]Vue/nuxt - how to access parents ref from child components

我在我的默认布局文件中注册了一个全局确认模式组件,然后我会尝试从我的 pages/index.vue 访问它,但是调用 this.$refs 只会返回一个空的 object。 将模态组件放在我的 pages/index.vue 中会起作用,但它会破坏我的全局确认模态的目的。

布局/default.vue

<template lang="pug">
v-app(v-if="show")
  v-main
    transition
      nuxt
  confirm(ref='confirm')
</template>
<script>
import confirm from '~/components/confirm.vue'
export default {
  components: { confirm },
  data: () => ({
    show: false
  }),
  async created() {
    const isAuth = await this.$store.dispatch("checkAuth")
    if (!isAuth) return this.$router.push("/login")
    this.show = true
  }
}
</script>

组件/确认.vue

<template>
  <v-dialog v-model="dialog" :max-width="options.width" @keydown.esc="cancel">
    <v-card>
      <v-toolbar dark :color="options.color" dense flat>
        <v-toolbar-title class="white--text">{{ title }}</v-toolbar-title>
      </v-toolbar>
      <v-card-text v-show="!!message">{{ message }}</v-card-text>
      <v-card-actions class="pt-0">
        <v-spacer></v-spacer>
        <v-btn color="primary darken-1" @click.native="agree">Yes</v-btn>
        <v-btn color="grey" @click.native="cancel">Cancel</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>
<script>
  export default {
    data: () => ({
      dialog: false,
      resolve: null,
      reject: null,
      message: null,
      title: null,
      options: {
        color: 'primary',
        width: 290
      }
    }),
    methods: {
      open(title, message, options) {
        this.dialog = true
        this.title = title
        this.message = message
        this.options = Object.assign(this.options, options)
        return new Promise((resolve, reject) => {
          this.resolve = resolve
          this.reject = reject
        })
      },
      agree() {
        this.resolve(true)
        this.dialog = false
      },
      cancel() {
        this.resolve(false)
        this.dialog = false
      }
    }
  }
</script>

然后我想像这样从我的 pages/index.vue 调用它(如果 ref 在这里,它会起作用,但我想要一个全局确认模式)

methods: {
    async openConfirm() {
      console.log("openConfirm")
       if (await this.$refs.confirm.open('Delete', 'Are you sure?', { color: 'red' })) {
         console.log('--yes')
       }else{
         console.log('--no')
       }
    },

简短的回答是:不要像那样滥用 $ref 。 最终,它只会导致反模式包裹在反模式中。

与您要完成的确切任务相关的更详细的答案:我现在在几个 Vue 项目中解决了同样的问题(全局的,基于 promise 的确认对话框),这是迄今为止效果很好的方法:

  1. 将确认对话框设置为它自己的独立“模块”,以便您可以使用两行将其添加到 main.js:
import ConfirmModule from './modules/confirm';
Vue.use(ConfirmModule);

(旁白:还有其他几个“全局模块化组件”,如警报等......)

  1. 使用 JS 文件编排设置过程、promise 管理和组件实例化。 例如:
import vuetify from '@/plugins/vuetify';
import confirmDialog from './confirm-dialog.vue';

export default {
  install(Vue) {
    const $confirm = (title, text, options) => {
      const promise = new Promise((resolve, reject) => {
        try {
          let dlg = true;
          const props = {
            title, text, options, dlg,
          };
          const on = { };
          const comp = new Vue({
            vuetify,
            render: (h) => h(confirmDialog, { props, on }),
          });
          on.confirmed = (val) => {
            dlg = false;
            resolve(val);
            window.setTimeout(() => comp.$destroy(), 100);
          };

          comp.$mount();
          document.getElementById('app').appendChild(comp.$el);
        } catch (err) {
          reject(err);
        }
      });
      return promise;
    };

    Vue.prototype.$confirm = $confirm;
  },
};
  1. 将它挂载到 Vue.prototype,这样你就可以在你的应用程序的任何组件中使用它,只需调用: this.$confirm(...)

  2. 当你构建你的 Vue 组件(confirm-dialog.vue)时,你只需要单向绑定标题、文本和选项的道具,单向绑定 dlg 道具到对话框,或者通过设置双向绑定具有 getter 和 setter 的计算属性...无论哪种方式...

  3. 如果用户确认,则发出一个带有true的“已确认”事件。 所以,从confirm-dialog.vue 组件: this.$emit('confirmed', true);

  4. 如果他们关闭对话框,或单击“否”,则发出 false 以便 promise 不会挂起: this.$emit('confirmed', false);

  5. 现在,从任何组件中,您都可以像这样使用它:

methods: {
  confirmTheThing() {
    this.$confirm('Do the thing', 'Are you really sure?', { color: 'red' })
      .then(confirmed => {
        if (confirmed) {
          console.log('Well OK then!');
        } else {
          console.log('Eh, maybe next time...');
        }
      });
  }
}

在 nuxt 项目的默认布局中,放置组件,如下所示Confirm

    <v-main>
      <v-container fluid>
        <nuxt />
        <Confirm ref="confirm" />
      </v-container>
    </v-main>

那么组件的open方法可以如下使用:

const confirmed = await this.$root.$children[2].$refs.confirm.open(...)
if (!confirmed) {
  return // user cancelled, stop here
}
// user confirmed, proceed

棘手的事情是如何找到布局中包含的组件。 $root.$children[2]部分似乎在开发阶段工作,但一旦部署,它必须是$root.$children[1]

所以我最终做了以下事情:

  // assume default.vue has data called 'COPYRIGHT_TEXT'
  const child = this.$root.$children.find(x => x.COPYRIGHT_TEXT)
  if (child) {
    const confirm = child.$refs.confirm
    if (confirm) {
      return await confirm.open(...)
    }
  }
  return false

背景:我的项目正在生产中,但提出了一个新要求,即在以特定模式保存之前获得确认。 我可以使用单向event bus ,但要做到这一点,确认后的代码 rest 必须重构才能在每个保存位置作为回调传递。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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