In vue development, how to use the content in the external js file in the template

In vue2, if you want to access the content defined in the external js file in the page template template, such as functions, it is troublesome. Let’s look at a specific example. The external server.js file is as follows:

const SERVER_IMAGE_BASE_URL = 'http://42.51.17.36:888';


export const getImageUrl = url=>{
	return SERVER_IMAGE_BASE_URL + url;
}

 If you want to use it in a vue file, you can use the following two methods. If you want to use it in multiple pages, it is best to use the second method.

method one:

Import the getImageUrl method defined in the server.js file in the script, and define the function in methods, the code is as follows:

<script>
	import {getImageUrl} from '@/utils/server.js'
	export default {
		data() {
			return {
			}
		},
		methods: {
			getUrl(url){
				return getImageUrl(url);
			}
		}
	}
</script>

In this way, in the template, it can be used like this:

<span>{
   
   {getUrl('/abc/a.jpg')}}</span>

Method Two:

Use instructions to inject functions into Vue.

(1) Introduce the js file server.js where the function is located in main.js

import { getImageUrl } from '@/utils/server'

(2) In the main.js file, use the directive to inject the above method.

const Plugin = {
	install(vue,options){
		vue.prototype.getImageUrl = getImageUrl;
	}
}
Vue.use(Plugin)

(3) The method getImageUrl can be used directly in the template, as follows:

<text>{
   
   {getImageUrl('/abc/b.jpg')}}</text>

It is more convenient and simple to use in vue3. But we need to use setup syntactic sugar, we only need to introduce the method in server.js in the script tag to use the function in the template.

<script setup>
import { get_img_url } from '../utils/urls';
</script>
 <img :src="get_img_url(abc.png)" alt="">

Guess you like

Origin blog.csdn.net/sweetsoft/article/details/130702638