【问题标题】:Make data and methods reusable in Vue js使数据和方法在 Vue js 中可重用
【发布时间】:2022-01-08 09:57:58
【问题描述】:

假设我在 vue 中有这样的脚本

<script>
export default {
  name: "BaseCardAnnotationOption",
  data() {
    return {
      includeAnnotations1: false,
      embedIntoImage: null,
      burnIntoImage: null,
      burnReduction1: false,
      maintainColor1: false,
      annotationOption1: null
    };
  },
  methods: {
    deselectDisabled() {
      return this.includeAnnotations1 === false
        ? ((this.annotationOption1 = null), (this.maintainColor1 = false))
        : ((this.annotationOption1 = 0), (this.maintainColor1 = false));
    }
  }
};
</script>

我在其他 4 或 5 个地方使用数据变量和方法。有没有办法我可以将所有这些放在一个新文件中,并在需要时从组件中调用它们。谢谢

【问题讨论】:

标签: vue.js vuetify.js


【解决方案1】:

您可以使用 mixins 来定义一些选项并在您的组件中重复使用它们,创建一个名为 someMixins.js 的文件,其内容如下:


export default const someMixins={
data() {
    return {
      includeAnnotations1: false,
      embedIntoImage: null,
      burnIntoImage: null,
      burnReduction1: false,
      maintainColor1: false,
      annotationOption1: null
    };
  },
  methods: {
    deselectDisabled() {
      return this.includeAnnotations1 === false
        ? ((this.annotationOption1 = null), (this.maintainColor1 = false))
        : ((this.annotationOption1 = 0), (this.maintainColor1 = false));
    }
  }

}

然后将其导入组件内部并使用如下:

<script>
import someMixins from 'path/to/someMixins.js'
export default {
  name: "BaseCardAnnotationOption",
  mixins:[someMixins]
}

【讨论】:

    【解决方案2】:

    只是对 Boussadjra Brahim 响应的补充,如果您使用的是 Vue 3,则可以在整个代码的“脚本设置”中导入您的函数。

    在 '../module.js' 之类的文件或您喜欢的其他文件中:

    export function deselectDisabled() {
    
    // Here you will need to modify and adapt your function to use callbacks. 
    
    }
    

    然后你可以导入它并像这样使用它:

    <script setup>
    import { deselectDisabled } from './module.js
    // Now you can use your function all over your vue file.
    
    ...
    
    </script>
    

    vue 3 正在实施新的“语法糖”,它对大型项目非常有帮助。您可以在此处查看更多信息: https://v3.vuejs.org/api/sfc-script-setup.html

    【讨论】:

      猜你喜欢
      • 2020-09-01
      • 1970-01-01
      • 2018-12-12
      • 2016-10-06
      • 1970-01-01
      • 2019-12-04
      • 2018-11-08
      • 2018-03-22
      • 1970-01-01
      相关资源
      最近更新 更多