随机生成一句话
// ==UserScript==
// @name 随机生成一句话
// @namespace http://tampermonkey.net/
// @version 0.1
// @description 随机生成一句话,用来学习脚本中使用vue。以及如何调用接口
// @author You
// @match *://*/*
// @icon https://www.google.com/s2/favicons?domain=tampermonkey.net.cn
// @grant unsafeWindow
// @run-at document-start
// @grant GM_addStyle
// @connect api.szfx.top
// @grant GM_xmlhttpRequest
// ==/UserScript==
// 引入vue3.js
let script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.src = "https://cdn.jsdelivr.net/npm/vue@next";
// 引入element,这个样式一会显示一会不显示,很迷,所以我没用,这里记录一下。到时候什么问题再说
document.documentElement.appendChild(script);
let link= document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.href= "https://unpkg.com/element-plus/dist/index.css";
document.documentElement.appendChild(link);
let elscript= document.createElement('script');
elscript.setAttribute('type', 'text/javascript');
elscript.src = "https://unpkg.com/element-plus";
document.documentElement.appendChild(elscript);
window.onload=()=>{
let text=`<div id="app">
<div class="search">
<button @click="search">点击随机生成</button>
<div>
<textarea cols="30" rows="10" >{{textContent}}</textarea>
</div>
</div>
</div>`
var el=document.createElement('div')
el.innerHTML=text;
document.body.append(el)
const App = {
data() {
return {
input: "",
textContent:"嗨嗨嗨"
};
},
methods: {
// 这里注意一下this的指向,注意一下就行。最好直接把里面写成箭头函数
// onload是回调函数,指向的应该是关于xhr的东西
search(){
console.log(this);
let that = this;
GM_xmlhttpRequest({
method: "GET",
responseType: "json",
url: "https://api.szfx.top/yiyan",
onload: function (xhr) {
console.log(xhr);
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
console.log(this);
that.textContent = xhr.responseText;
} else {
console.log("获取数据失败");
}
},
});
}
}
};
const app = Vue.createApp(App);
app.use(ElementPlus);
app.mount("#app");
}
GM_addStyle(`
#app {
position: absolute;
top: 0vh;
right: 10vw;
background: #fb7d7d;
width: 220px;
height: 200px;
z-index:999;
}
.search input {
height:30px;
}
`)