Vue/nuxt - 如何从子组件访问父引用 [英] Vue/nuxt - how to access parents ref from child components

查看:95
本文介绍了Vue/nuxt - 如何从子组件访问父引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a global confirm modal component that is registered on my default layout file, I would then try to access it from my pages/index.vue but the calling this.$refs there would just return an empty object. Placing the modal component in my pages/index.vue will work but it will defeat the purpose of my global confirm modal.

布局/default.vue

layouts/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>

components/confirm.vue

components/confirm.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 在这里它会工作,但我想要一个全局确认模式)

I would then like to call it from my pages/index.vue like this (it would work if the ref is here but I would like a global confirm modal)

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.最终,它只会导致反模式包裹在反模式中.

The short answer is: Don't abuse $ref like that. Ultimately, it will just lead to anti-patterns wrapped in anti-patterns.

与您要完成的确切任务相关的更详细的答案:我现在已经在一些 Vue 项目中处理了完全相同的事情(全局的、基于承诺的确认对话框),到目前为止,这是非常有效的:

More detailed answer related to the exact task you're trying to accomplish: I've tackled this exact same thing (global, promise based confirmation dialogs) on a few Vue projects now, and this is what has worked really well so far:

  1. 将确认对话框设置为其独立的模块",以便您可以使用两行将其添加到 main.js:

import ConfirmModule from './modules/confirm';
Vue.use(ConfirmModule);

(旁注:还有其他一些全局模块化组件",例如警报等...)

(side point: there's a couple other of these 'global modular components' like alerts, etc...)

  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(...)

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

When you build your Vue component (confirm-dialog.vue) you need only one-way bind your props for title, text and options, one-way bind the dlg prop to the dialog, or else setup a two-way binding through a computed property with a getter and setter... either way...

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

emit a "confirmed" event with true if the user confirms. So, from the confirm-dialog.vue component: this.$emit('confirmed', true);

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

If they dismiss the dialog, or click 'no' then emit false so that the promise doesn't hang around: this.$emit('confirmed', false);

现在,您可以从任何组件使用它:

Now, from any component, you can use it like so:

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...');
        }
      });
  }
}

这篇关于Vue/nuxt - 如何从子组件访问父引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆