不能在函数外使用变量。给出未定义
Can't use variable outside of the function. Gives undefined
我有这个缩短 url 的 npm 包,它没有太多文档。它接受这个“this.src”url 并将其缩短。我想在 html 中使用“url”元素,我该怎么做?它给了我未定义的。
<template>
<div id="image">
<h2>Upload Successful</h2>
<a target="_blank" :href="src">Image Link</a>
<button @click="shorter">Short URL</button>
<p>{{ urlShare }}DD</p> //GIVES UNDEFINED
<div class="img">
<a target="_blank" :href="src"> <img :src="src" alt="" /> </a>
</div>
</div>
</template>
<script>
var shortUrl = require("node-url-shortener");
export default {
name: "Image",
props: ["src"],
data() {
return {
urlShare: null, //GIVES UNDEFINED
};
},
methods: {
shorter() {
this.urlShare = shortUrl.short(this.src, function (err, url) {
return url;
});
console.log(this.urlShare); //GIVES UNDEFINED
},
},
};
</script>
我不熟悉那个包,但看起来它使用的是回调而不是返回值。试试这个:
shorter() {
shortUrl.short(this.src, (err, url) => {
this.urlShare = url;
console.log(this.urlShare);
});
},
我有这个缩短 url 的 npm 包,它没有太多文档。它接受这个“this.src”url 并将其缩短。我想在 html 中使用“url”元素,我该怎么做?它给了我未定义的。
<template>
<div id="image">
<h2>Upload Successful</h2>
<a target="_blank" :href="src">Image Link</a>
<button @click="shorter">Short URL</button>
<p>{{ urlShare }}DD</p> //GIVES UNDEFINED
<div class="img">
<a target="_blank" :href="src"> <img :src="src" alt="" /> </a>
</div>
</div>
</template>
<script>
var shortUrl = require("node-url-shortener");
export default {
name: "Image",
props: ["src"],
data() {
return {
urlShare: null, //GIVES UNDEFINED
};
},
methods: {
shorter() {
this.urlShare = shortUrl.short(this.src, function (err, url) {
return url;
});
console.log(this.urlShare); //GIVES UNDEFINED
},
},
};
</script>
我不熟悉那个包,但看起来它使用的是回调而不是返回值。试试这个:
shorter() {
shortUrl.short(this.src, (err, url) => {
this.urlShare = url;
console.log(this.urlShare);
});
},