vue避免使用mixins_用Mixins扩展Vue组件

vue避免使用mixins

When it’s a side project or something little, the DRY concept may not be tightly upheld. Yikes it’s just a “simple demo”, nothing large. When we begin to build large chunks of code not necessarily production level, thoughts of reusability and maintainability begin to come in. Must these methods be repeated? How do we replace this and that with functions? When using frameworks such as Vue, even with its ease of use and gradual learning curve, it becomes cumbersome to write and keep track of repetitive options in components. These options may be component data or hook methods such as “created”, “mounted” and even “methods”. This is where Mixins come in.

当是辅助项目或其他一些项目时,DRY概念可能不会得到严格支持。 只是一个“简单的演示”,没什么大不了的。 当我们开始构建不一定是生产级别的大代码块时,关于可重用性和可维护性的想法就开始出现。这些方法是否必须重复? 我们如何用功能替换这个? 当使用诸如Vue之类的框架时,即使其易用性和渐进式学习曲线,编写和跟踪组件中的重复选项也变得很麻烦。 这些选项可以是组件数据或挂钩方法,例如“创建”,“安装”甚至“方法”。 这是Mixins进来的地方。

Mixins in Vue, gives us the ability to wrap our reusable options in a “variable container” which can be used anywhere in the script. And by anywhere, even globally, but that would be treated with caution.

Vue中的Mixins使我们能够将可重复使用的选项包装在“变量容器”中,该变量可以在脚本中的任何位置使用。 在任何地方, 甚至在全球范围内,都应谨慎对待。

什么是Mixin? ( What is a Mixin? )

As the name goes - “Mix - In”, Mixin gives us a way to distribute reusable functionality in Vue components. These reusable functions are merged with existing functions. In our Vue component, we specify the mixin object with:

顾名思义-“混合-输入”,Mixin为我们提供了一种在Vue组件中分发可重用功能的方法。 这些可重用功能与现有功能合并。 在我们的Vue组件中,我们使用以下命令指定mixin对象:

const myMixin = {
  created(){
    console.log("It works!")
  }
}
var app = new Vue({
  el: '#root',
  mixins: [myMixin]
})// It works!

Using mixins, whichever options specified in the mixin are immediately merged with the Vue component’s options. Multiple mixins can be specified in the mixin array of the component. Once specified, all mixin options are imported to the parent component.

使用mixin,mixin中指定的任何选项都会立即与Vue组件的选项合并。 可以在组件的mixin数组中指定多个mixin。 指定后,所有mixin选项都将导入到父组件。

合并选项和冲突 ( Merging Options and Conflicts )

Now we may think, what if there are conflicting options between hook functions from a mixin and that of the parent component, which takes precedence? When mixins are passed in components, Vue moves all hook functions such as created and mounted imported via the mixin into an array of options, including the options of the parent component. The parent component options are called last.

现在我们可能会想,如果混入的钩子函数与父组件的钩子函数之间有冲突的选项怎么办? 当在组件中传递mixin时,Vue会将所有通过mixin 创建挂载的钩子函数(通过混合引入)移动到一组选项中,包括父组件的选项。 父组件选项称为last

const myMixin = {
  created(){
    console.log("Welcome aboard")
  }
}

new Vue({
  el: '#root',
  mixins:[myMixin],
  created(){
    console.log("Ahoy mate!")
  }
})
//Welcome aboard
//Ahoy mate!

There are options which expect objects, like the methods object. In such cases where there is a conflict between options, the component options take precedence.

有一些期望对象的选项,例如methods对象。 在选项之间存在冲突的情况下, 组件选项优先。

const myMixin = {
  created(){
    console.log("Welcome aboard")
  },
  methods:{
    name(){
      this.myName = prompt("Input Name")
    }
  }
}

new Vue({
  el:"#root",
  mixins:[myMixin],
  data:{
    myName:""
  },
  created(){
    console.log("Ahoy mate!")
  },
  methods:{
    name(){
      this.myName = "Christian John"
      console.log(this.myName)
    }
  }
})

//Console Logs
> Welcome aboard
> Ahoy mate!
> Christian John

Notice how the name() method in the mixin was disregarded during the conflict. The prompt to input name never runs.

注意在冲突期间如何忽略mixin中的name()方法。 输入名称的提示永远不会运行。

Note: The Component Options are always right.

注意:组件选项始终正确。

Here is a Codepen demo of a simple Vue counter app using mixin:

这是一个使用mixin的简单Vue计数器应用程序的Codepen演示:

全局混合 ( Global Mixins )

In some cases, there is the need to extend the functionality of Vue or apply an option to all Vue components available in our application. Feels a bit scary? Yeah, mixins can be applied globally to affect all components in Vue.

在某些情况下,需要扩展Vue的功能或对我们应用程序中所有可用的Vue组件应用一个选项。 感觉有点吓人吗? 是的,mixins可以全局应用以影响Vue中的所有组件。

Vue . mixin ( {
  created ( ) {
  console . log ( "We wilding!" )
  }
} )

new Vue ( {
  el : '#data'
} )

//Console
> We wilding !

The global mixin is created above the Vue instance, and we would have the mixin options spread across all components with the console running wild. This can be useful, during test, and debugging or third party libraries maybe, but we can see the potential harm that could be done if misused.

全局mixin是在Vue实例上方创建的,我们可以在控制台疯狂运行的情况下将mixin选项分布在所有组件上。 这在测试期间可能有用,并且可能在调试或第三方库时使用,但是我们可以看到如果滥用可能造成的潜在危害。

在CLI开发模式下使用Mixins ( Using Mixins in CLI Development Mode )

Using the Vue CLI, mixins can be specified anywhere in the project folder but preferably within /src/mixins for ease of access. Once mixins are created in a .js file and exposed with the export keyword, they can be imported in any component with the import keyword and its file path.

使用Vue CLI,可以在项目文件夹中的任何位置指定mixins,但最好在/src/mixins ,以便于访问。 在.js文件中创建混入文件并使用export关键字公开后,即可使用import关键字及其文件路径将混入文件导入任何组件。

src/mixins/numeroUno.js

src / mixins / numeroUno.js

export const = {
  created ( ) {
    console . log ( "Welcome aboard" )
  } ,
  methods : {
    name ( ) {
      this . myName = prompt ( "Input Name" )
    }
  }
}

In the component, wherever it is in our project folder, we import the mixin object:

在组件中的项目文件夹中的任何位置,我们都将导入mixin对象:

import { numeroUno } from < file path >

export default {
  name : 'main' ,
  mixin : [ numeroUno ]
}

Even though we are importing a mixin object, lifecycle options are still available via the mixin and can be used in the component imported to.

即使我们要导入mixin对象,生命周期选项仍然可以通过mixin使用,并且可以在导入到的组件中使用。

结论 ( Conclusion )

Don’t Repeat Yourself. In a bid to follow this rule, we have seen how the power of Vue mixins can be utilized to minimize code and maximize the functionality of components. This comes in handy when multiple components are defined across our application with similar options. Components are created in the first place to introduce reusability, mixins are created to introduce reusability in our components. Mixins can also be created globally to function across all Vue components, such access if wrongly used can be dastardly.

不要重复自己。 为了遵循该规则,我们已经了解了如何利用Vue mixins的功能来最小化代码并最大化组件的功能。 当在我们的应用程序中使用相似的选项定义了多个组件时,这将派上用场。 首先创建组件是为了引入可重用性,创建混合是为了引入组件中的可重用性。 还可以全局创建Mixins,以在所有Vue组件上正常工作,如果使用不当,则可能会混在一起。

翻译自: https://scotch.io/tutorials/extending-vue-components-with-mixins

vue避免使用mixins

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Vue mixins的方法如下: 1. 在src目录下创建一个mixins文件夹,并在该文件夹下新建一个myMixins.js文件。 2. 在myMixins.js文件中,定义一个对象,并在该对象中定义你想要在组件中复用的功能选项,如data、components、methods、created、computed等。 3. 使用export导出该对象。 4. 在需要使用mixins组件中,通过import引入myMixins.js文件,并在组件mixins选项中添加该对象。 5. 在组件中可以直接使用mixins对象中定义的功能选项,这样可以提高代码的重用性,并使代码保持干净和易于维护。 示例代码如下: ```javascript // 在myMixins.js文件中定义mixins对象 export const myMixins = { data() { return { // 定义共用的data属性 } }, methods: { // 定义共用的方法 }, created() { // 定义共用的created钩子函数 }, // 其他共用的功能选项 } // 在需要使用mixins组件中引入并使用mixins对象 import { myMixins } from "@/mixins/myMixins.js"; export default { mixins: [myMixins], // 组件的其他选项 } ``` 通过以上步骤,你可以轻松地在Vue组件使用mixins,从而实现代码的重用和提高开发效率。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Vue — 详解mixins混入使用](https://blog.csdn.net/qq_42198495/article/details/118424355)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值