vue调用组件和程序集的方法

vue.js里面,代码复用,可以采用组件形式;如果是js方法复用,不涉及UI,当然也可以像之前那样,直接引用js文件。

如果采用组件,可以采用映射(this.$refs)的方式来引用组件中methods里的方法。js文件则不必多言。

1、组件Com2.vue

<template>
  <div>
    大家对你说
  </div>  
</template>

<script>
export default {
  methods:{
    say(s) {
      let what = s ? s : '加油!我们等着你回来!'; 
      alert(what)
    }
  }
}
</script>

2、程序集methods.js

export default {
  say(s) {
    let what = s ? s : '挺住!你定会度过难关!'; 
    alert(what)
  }
}

3、调用它们的页面

<template>
  <div>
    <div><Comp2 ref="comp2" /></div>
    <div>
      <button @click="look" title="听着!">听着!</button>
      <button @click="look2" title="嘿!!">嘿!</button>
    </div>
  </div>  
</template>

<script>
import Comp2 from './Comp2.vue'
import methods from './methods.js'

export default{
  components:{
    Comp2
  },
  methods:{
    look(){
      this.$refs.comp2.say();
    },
    look2(){
      methods.say()
    }
  }
}
</script>

4、运行结果
在这里插入图片描述


2021.07.13
以上调用组件方法,是父组件或页面调用子组件的模式。那么子组件如何调用父组件的方法呢?

一、子组件调用父组件方法

方法类似:

this.$parent.方法名()

子组件也可以通过发射将事件传递给父组件,父组件接收后触发相关动作。

二、子组件触发父组件

子组件:

<template>
	<div>
		<Button type="primary" @click="search">查询</Button>
	</div>
</template>

<script>
export default {
  methods: {
    search () {
      this.$emit('getQueryResult', 1000)
    }
  }
}
</script>

父组件或包含子组件的页面

<template>
	<div>
		<Query @getQueryResult="getQueryResult" />
	</div>
</template>

<script>
import Query from './_query.vue'

export default {
  components: {
    Query
  },
  methods: {
	getQueryResult (data) {
      。。。
    }
  }
}
</script>

三、父组件把方法传入子组件中

我觉得不是很好,不说也罢。

参考文章:
Vue子组件调用父组件的方法


2021.07.16

import js,如

import methods from './methods.js'

在浏览器中调试,定位methods时会提示该对象未定义。但是并不影响methods.say()这个方法执行。真是奇怪。

posted on 2021-07-07 20:03  左直拳  阅读(2)  评论(0)    收藏  举报  来源

导航