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

如何解决Vue / Nuxt-如何从子组件访问父引用

我有一个全局确认模式组件,该组件已在我的默认布局文件中注册, 然后,我尝试从我的pages / index.vue访问它,但是调用this。$ refs只会返回一个空对象。将模式组件放置在我的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>

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中这样调用它(如果引用在这里就可以了,但是我想要一个全局确认模式)

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项目上解决了相同的问题(全局,基于诺言的确认对话框),到目前为止,这确实非常有效:

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

(要点:这些“全局模块化组件”还有其他一些,例如警报等)

  1. 使用JS文件来协调设置过程,承诺管理和组件实例化。例如:
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,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. 如果用户确认,
  4. 使用true发出“已确认”事件。因此,从confirm-dialog.vue组件中:this.$emit('confirmed',true);

  5. 如果他们关闭该对话框,或单击“否”,则发出false,以使诺言不再出现:this.$emit('confirmed',false);

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

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,但要做到这一点,必须重构确认后的其余代码,以便在每个保存位置作为回调传递。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-